【发布时间】:2016-12-17 21:30:15
【问题描述】:
我是 chrome 扩展的新手,我遇到了一个问题。 单击我的扩展程序图标时,我会运行一个脚本:
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript({
"file": "enterIonis.js"
});
});
此脚本从打开的选项卡中获取一些信息,然后更改选项卡 url 以加载新页面。然后,此脚本需要等待新页面完全加载才能与之交互。为此,它打开一个端口并向使用chrome.tabs.onUpdated 侦听器的后台页面发送消息。背景页面应该向内容脚本发送消息/回调,告诉它现在可以与选项卡交互。
background.js:
var _port;
var goodUrl;
chrome.runtime.onConnect.addListener(function(port) {
console.assert(port.name == "enterIonis");
port.onMessage.addListener(function(msg) {
goodUrl = msg.url;
_port = port;
});
});
chrome.tabs.onUpdated.addListener(function ( tabId, changeInfo, tab ){
if ( changeInfo.status === "complete" ){
chrome.tabs.query({'active': true, 'lastFocusedWindow': true}, function (tabs) {
var currentUrl = tab.url;
if(currentUrl == goodUrl){
//should send a callback to content script here
_port.postMessage({result: "ok"});
}
});
}
});
content_script.js
//interacting with DOM elements
...
// sending a message to background.js
var port = chrome.runtime.connect({name: "enterIonis"});
port.postMessage({url:href});
port.onMessage.addListener(function(msg){
// here is where the message from the background telling the tab is ready should arrive
alert(msg.result);
});
问题是当我尝试使用第一条消息中的端口时,我收到以下错误:Error in response to tabs.query: Error: Attempting to use a disconnected port object
如何重新连接端口?或者有没有其他方法可以实现我的目标?
【问题讨论】:
-
不清楚为什么不能从后台脚本进行操作,而是将脚本注入页面并设置通信。
-
请edit 成为主题的问题:包括一个完整 minimal reproducible example 重复问题。包括一个manifest.json,一些背景/内容/弹出脚本/HTML。寻求调试帮助的问题(“为什么这段代码不起作用?”)必须包括:►所需的行为,►特定问题或错误和►必要的最短代码重现它在问题本身。没有明确问题陈述的问题对其他读者没有用处。请参阅:“如何创建 minimal reproducible example”、What topics can I ask about here? 和 How to Ask。
-
虽然您已经提供了足够的信息,但我们可以很好地猜测关于可能会发生什么,而无需您提供完整minimal reproducible example在问题中,我们无法知道猜测是否正确。
-
@pvg 我需要内容脚本来与页面上的 DOM 元素进行交互
标签: javascript google-chrome google-chrome-extension tabs