Javascript 如何在网页中从后台脚本到脚本触发函数?

Javascript 如何在网页中从后台脚本到脚本触发函数?,javascript,google-chrome,Javascript,Google Chrome,我目前正在编写一个chrome扩展。现在我想在从网页加载的脚本中调用一个函数 chrome.runtime.sendMessage({ test: 'hello' }, function (response) { console.log(response); }); 我已经尝试从background.js向我的网页发送一条简单的消息 chrome.runtime.sendMessage({ test: 'hello' }, function (response) { conso

我目前正在编写一个chrome扩展。现在我想在从网页加载的脚本中调用一个函数

chrome.runtime.sendMessage({ test: 'hello' }, function (response) {
    console.log(response);
});
我已经尝试从background.js向我的网页发送一条简单的消息

chrome.runtime.sendMessage({ test: 'hello' }, function (response) {
    console.log(response);
});
抛出错误:“未检查的运行时。lastError:无法建立连接。接收端不存在。”

在我的网页脚本中:

chrome.runtime.onMessageExternal.addListener(function (callback) {
    console.log(callback);
});
抛出错误:“TypeError:无法读取未定义的属性'addListener'”

如何从background.js向someWebPageScript.js发送消息


提前感谢。

第一个问题:“someWebPageScript.js”是您的“content.js”脚本,还是您的清单中声明的内容(这也可能有助于查看)

如果是这样,并且您正试图将一条消息从后台脚本传递到内容脚本,您可能需要仔细阅读Chrome消息传递文档。将消息传递给内容脚本看起来更像:

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
侦听器用于接收来自其他扩展的消息

希望这有帮助。
-brent

第一个问题:“someWebPageScript.js”是您的“content.js”脚本,还是您的清单中声明的内容(这也可能有助于查看)

如果是这样,并且您正试图将一条消息从后台脚本传递到内容脚本,您可能需要仔细阅读Chrome消息传递文档。将消息传递给内容脚本看起来更像:

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
侦听器用于接收来自其他扩展的消息

希望这有帮助。 -布伦特