gpt4 book ai didi

javascript - ContextMenuItem 上下文函数未执行

转载 作者:行者123 更新时间:2023-11-28 01:51:11 25 4
gpt4 key购买 nike

我希望仅当单击的节点是链接(即 href 是磁力链接或 torrent 链接)时我的上下文菜单项才可见。但是项目对于所有链接都是可见的,因为上下文函数没有执行,任何人都可以帮助为什么上下文函数没有执行吗?

代码如下:

exports.main = function() {
var cm = require("sdk/context-menu");

var contextCode = ' self.on("context", function (node) { '+
' while(node.nodeName!="A") { node = node.parentNode; } '+
' var pat_magnet = /^magnet:/i; ' +
' var pat_torrent = /.torrent$/i; ' +
' if(pat_torrent.test(node.href) || pat_magnet.test(node.href)) { return true; } '+
' else { return false; } '+
' }); ';

var clickCode = ' self.on("click", function(node,data){ '+
' while(node.nodeName!="A") { node = node.parentNode; } '+
' var pat_hash = /[0-9abcdef]{32,40}/i; ' +
' var result = node.href.match(pat_hash); '+
' var hash = "" '
' if(result != null) { hash=result[0]; } '+
' var xhr = new XMLHttpRequest(); '+
' if(hash != "") { '+
' var apiCall = "https://www.furk.net/api/dl/add?api_key=*************&info_hash="+hash; '+
' } '+
' else{ '+
' var apiCall = "https://www.furk.net/api/dl/add?api_key=*************&url="+encodeURI(node.href); '+
' } '+
' xhr.open("GET",apiCall,true); '+
' xhr.onreadystatechange = function(){ if(xhr.readyState = 4) { if (xhr.response.status = "ok") { alert("Torrent added to Furk."); } else { alert("Torrent could not be added to Furk."); } } } '+
' xhr.send(null); '+
' });';
cm.Item({
label: "Add to Furk",
context: cm.SelectorContext("a[href]"),
contentScript: contextCode + clickCode
});
};

最佳答案

请始终发布可以在将来直接尝试的独立示例。

现在回到您的问题:内容脚本实际上存在语法错误。

以下行:

' var pat_torrent = /.torrent$/i ' +

缺少分号,应该是:

' var pat_torrent = /.torrent$/i; ' +

自动分号插入(ASI)在这里不起作用的原因是:“代码”实际上是一个没有换行符的字符串。如果有换行符,那么 ASI 就会起作用。无论如何,不​​内联复杂内容脚本的另一个原因。看看contentScriptFile .

这个错误实际上已被记录,但演示很糟糕。在浏览器控制台中:

[20:57:51.707] [object Error] (expandable)

在终端中:

console.error: context-magnet: Message: SyntaxError: missing ; before statement

这是一个固定的、可重现的示例:

var cm = require("sdk/context-menu");
var contextCode = ' self.on("context", function (node) { '+
' while(node.nodeName!="A") { node = node.parentNode; } '+
' var pat_magnet = /^magnet:/i; ' +
' var pat_torrent = /.torrent$/i; ' +
' if(pat_torrent.test(node.href) || pat_magnet.test(node.href)) { return true; } '+
' else { return false; } '+
' }); ';
cm.Item({
label: "magnet test",
context: cm.SelectorContext("a[href]"),
contentScript: contextCode
});

编辑 ' var hash = ""' 也有同样的问题,并且可能还有其他此类错误,我错过了浏览这个新代码。正如我已经说过的,对于较长的脚本,请使用 contentScriptFile 而不是 contentScript

再次编辑

这里是a builder使用 contentScriptFile,我还修复了其他几个错误,其中最重要的是:

  • 使用permissions这样 XHR 才能工作。
  • 正确设置 XHR 以使用 responseTypeoverrideMimeType()
  • 使用 onload/onerror 而不是 onreadystatechange

关于javascript - ContextMenuItem 上下文函数未执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19690138/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com