Google chrome extension chrome.tabs.sendMessage:&x201C;端口错误:无法建立连接。接收端不存在”;仅在缓存页上
我已经通读了所有相关的错误,我认为这个案例有点不同。我正在尝试将消息从后台上下文发送到内容脚本。例如Google chrome extension chrome.tabs.sendMessage:&x201C;端口错误:无法建立连接。接收端不存在”;仅在缓存页上,google-chrome-extension,Google Chrome Extension,我已经通读了所有相关的错误,我认为这个案例有点不同。我正在尝试将消息从后台上下文发送到内容脚本。例如 chrome.tabs.query({ currentWindow: true, active: true }, function(tabs){ chrome.tabs.sendMessage(tabs[0].id, { name: name, args: args }, function(response){ if
chrome.tabs.query({
currentWindow: true,
active: true
}, function(tabs){
chrome.tabs.sendMessage(tabs[0].id, {
name: name,
args: args
}, function(response){
if (!response) return callback('You tried to message a tab that does not exist');
});
});
如果在安装扩展之前加载了open选项卡,则会引发端口错误。要重新创建:
端口错误
是否有解决方法?不发送消息,而是使用回调结果:
chrome.tabs.query({
currentWindow:对,
主动:正确
},功能(选项卡){
chrome.tabs.executeScript(制表符[0].id{
代码:“location.href”,
runAt:“文档开始”,
allFrames:false//在顶级帧上运行仅获取
//只有一个结果
},功能(结果){
var结果=结果[0];
console.log(result);//示例
});
});
您也可以使用
file:'code.js'
而不是code:'…'
来运行文件,而不是在字符串中指定代码。谢谢,我担心可能是这样。也许你马上就知道了——如果用户在同一个选项卡/url上重复调用浏览器操作,脚本是否会在该页面上重复执行,从而产生重复消息?@ChristopherCliff是的,但你可以保存一个变量,以查看脚本是否已经运行。例子: