【问题标题】:How to dynamically send chrome extension ID to a webpage for message passing如何将 chrome 扩展 ID 动态发送到网页以进行消息传递
【发布时间】:2016-03-28 05:24:28
【问题描述】:

我通过内容脚本在网页中注入了一个脚本。在脚本中,我使用 chrome.runtime.sendMessage 成功向后台脚本发送消息。但是我对 extensionId 进行了硬编码。如何在网页中动态注入扩展 ID 以将消息发送到后台脚本?

chrome.runtime.sendMessage(extensionIdHardCoded, {
      msg: data
    },
    function(response) {});

【问题讨论】:

  • 很遗憾,它必须是硬编码的。
  • @DanielHerr 在这种情况下我应该采取什么安全措施吗?我的扩展只是在前端操作了JS,在网页和后台脚本之间有回调。

标签: javascript google-chrome google-chrome-extension


【解决方案1】:

像这样使用chrome.runtime.id

chrome.runtime.sendMessage(chrome.runtime.id, {
    msg: data
},
function(response) {});

【讨论】:

  • 您误解了设置。代码在页面级别执行,不再访问 Chrome API(sendMessage 除外)。见Sending messages from web pages
  • 既然提到了chrome.runtime.id 并且很有用,我不打算投反对票。
【解决方案2】:

首先,如果您已经有内容脚本,则不必使用 externally_connectable 进行通信 - 您可以使用 use custom events 与将其转发到后台的内容脚本进行通信。


也就是说,您可以在注入脚本之前使用chrome.runtime.id 并将其传递给窗口上下文:

var script = document.createElement('script');
script.textContent = "var extensionId = " + JSON.stringify(chrome.runtime.id);
(document.head||document.documentElement).appendChild(script);
script.parentNode.removeChild(script);

/* now inject your script */

或者,您可以添加一个不可见的 DOM 节点,该节点将包含 ID 作为内容或某些属性,并从注入的脚本中读取。

【讨论】:

  • 我采取的第一条路线是先注入包含扩展ID的脚本,然后注入其他需要使用扩展ID的脚本。如果有人需要更多关于通过内容脚本注入脚本的不同方式的信息refer to this post
猜你喜欢
  • 1970-01-01
  • 2012-07-10
  • 2015-11-01
  • 1970-01-01
  • 2015-02-13
  • 2013-02-07
  • 1970-01-01
相关资源
最近更新 更多