【问题标题】:Communication between page and extension页面和扩展之间的通信
【发布时间】:2018-10-05 01:16:08
【问题描述】:

我开发了我的第一个 chrome 扩展。

我尝试从我的default_popup 调用该页面。

我尝试使用chrome.runtime.onMessage.addListenerchrome.runtime.sendMessage,但这不起作用。

我阅读了此页面https://developer.chrome.com/apps/messaging,但我不知道在哪里正确放置我的Listiner。

当我打开“默认弹出窗口”时,我需要在页面中调用一个事件并将某些内容返回给来自页面的“default_popup”。

更多解释:

实际上我在这个 content.js 中有一个 content.js,我可以通过调用 chrome.runtime.sendMessage 来调用 background.js,但它的调用速度很快。

页面的 DOM 没有足够的时间来加载。我的 content.js 在网页中注入了一些 .js 文件来与页面交互。

有没有办法从注入的页面调用 crhome.extension.sendMessage ?

有什么建议吗?

【问题讨论】:

  • 使用带有标签 ID 的 chrome.**tabs**.sendMessage 发送到内容脚本的 onMessage 侦听器 (example)。附言在文档链接中将 apps 替换为 extensions
  • @wOxxOm 感谢您的回答,但问题出在后台脚本我无法在我所在的网页上获取“html 内容”..
  • 嗯,如果I try to call the page 表示访问网页 DOM,那么您需要一个内容脚本。确保您已阅读扩展名architecture overview
  • @wOxxOm 抱歉,我意识到我不清楚。我添加了有关我的问题的更多详细信息。我已经有一个 content.js 文件
  • 如果没有实际代码,很难猜测这里究竟是什么问题,所以我只能建议阅读文档,学习demo extensions。如果您需要页面的 JS 上下文中的某些内容,请参阅 Access global js variables from js injected by a chrome extension

标签: google-chrome google-chrome-extension google-chrome-devtools


【解决方案1】:

好的,我找到了。

我们可以在background.js中注册一个事件

chrome.runtime.onMessageExternal.addListener(
 function (request, sender, sendResponse) {
   debugger;
   if (sender.url == blacklistedWebsite)
     return;  // don't allow this web page access
   if (request.openUrlInEditor)
     openUrl(request.openUrlInEditor);
 });

您需要在清单中放入正确的规则

"externally_connectable": {
  "matches": ["*://*.example.com/*"]
}

在您注入的页面之后:

    chrome.runtime.sendMessage(extensionID, { openUrlInEditor: "test" },
  function (response) {
    debugger;
    if (!response.success)
      handleError("est");
  });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多