javascript - 如何从后台脚本到网页脚本触发功能?

标签 javascript google-chrome

我目前正在编写一个 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/

相关文章:

javascript - 网络音频振荡器类型在 Chrome、Firefox 中不起作用吗?

javascript - 如何在 Google Chrome 中为 SpeechSynthesisUtterance 设置默认语音?

android - 用于 android 的 chrome 中的语音合成不加载声音

javascript - VueJS 换行符未正确呈现

javascript - 在 Node.JS 的回调中添加 flow.add() (asyncblok 模块内容)

javascript - js未定义错误index.html到其他js

javascript - 在 ES6 React .JS 中使用 Async/Await

javascript - Jquery 如果 keydown 和 keyup 事件触发禁用其他按键事件,则在 Chrome 中有效,但在 IE 和 Mozilla 中无效

python - 使用 selenium (Python) 运行两个不同版本的 chrome

javascript - 使用 JQuery 悬停缩放 div