我目前正在编写一个 Chrome 扩展。我现在想调用从网页加载的脚本内的函数。
我已经尝试从 background.js 向我的网页发送一条简单的消息。
chrome.runtime.sendMessage({ test: 'hello' }, function (response) {
console.log(response);
});
抛出错误:“未检查的runtime.lastError:无法建立连接。接收端不存在。”
在我的网页脚本上:
chrome.runtime.onMessageExternal.addListener(function (callback) {
console.log(callback);
});
抛出错误:“TypeError:无法读取未定义的属性“addListener””
如何将消息从 background.js 发送到 someWebPageScript.js?
提前致谢。
最佳答案
第一个问题:“someWebPageScript.js”是您的“content.js”脚本,还是 list 中声明的内容(这也可能有助于查看)?
如果是这样,并且您正在尝试将消息从后台脚本传递到内容脚本,您可能需要仔细阅读 Chrome 消息传递文档 here 。将消息传递给内容脚本看起来更像是:
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, function(response) {
console.log(response.farewell);
});
});
接收端(在内容脚本中)需要看起来更像这样:
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
console.log(sender.tab ?
"from a content script:" + sender.tab.url :
"from the extension");
if (request.greeting == "hello")
sendResponse({farewell: "goodbye"});
});
您使用的 chrome.runtime.onMessageExternal.addListener
监听器用于接收来自其他扩展程序的消息。
希望这有帮助。 -布伦特
关于javascript - 如何从后台脚本到网页脚本触发功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60469265/