我需要从后台脚本执行内容脚本,并将几个参数从后台脚本发送到内容脚本。我浏览了几个像这样的帮助页面......
https://developer.chrome.com/extensions/content_scripts#pi
...但仍然不知道如何组织它。在 Firefox 扩展中,我执行了以下操作:
后台脚本摘录:
browser.tabs.executeScript({
file: "content/login.js"
}).then(messageContent).catch(onError)
}
function messageContent() {
var gettingActiveTab = browser.tabs.query({active: true, currentWindow: true});
gettingActiveTab.then((tabs) => {
browser.tabs.sendMessage(tabs[0].id, {loginUserName: loginUserName, loginPassword: loginPassword});
});
}
内容脚本摘录:
function justDoTheJob(request, sender, sendResponse) {
var doc = window.content.document;
doc.getElementById("loginUserName").value = request.loginUserName;
doc.getElementById("loginPassword").value = request.loginPassword;
}
browser.runtime.onMessage.addListener(justDoTheJob);
但是当我在 Chrome 中执行类似操作时,我得到以下信息:
响应 tabs.query 时出错:TypeError:无法读取 Object.callback 中未定义的属性“then”
所以看来我使用了错误的语法,甚至根本就错误的结构。您能给我一些关于如何正确执行此操作的线索吗?
谢谢, 浣熊
最佳答案
正如 @qwOxxOm 在评论中指出的那样,您需要在 Chrome 中使用回调,例如,不要附加 then()
,而是将 then
中的函数移动到调用本身的参数链。否则它的使用方式几乎相同:
chrome.tabs.executeScript({file: "content/login.js"}, myCallback);
function callback(result) {
// handle result here
}
或类似:
function messageContent() {
chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
// sendMessage here
})
}
等等
错误处理有点不同,您会检查 lastError
而不是使用回调。
您还可以使用 Firefox 的 chrome
命名空间(这两个浏览器/命名空间在某些方面存在一些差异,您需要考虑)。
关于javascript - Chrome 扩展程序 : communication between background and content scripts,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46120792/