Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/google-chrome/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Chrome扩展消息传递:验证发件人_Javascript_Google Chrome_Google Chrome Extension - Fatal编程技术网

Javascript Chrome扩展消息传递:验证发件人

Javascript Chrome扩展消息传递:验证发件人,javascript,google-chrome,google-chrome-extension,Javascript,Google Chrome,Google Chrome Extension,我正在编写一个chrome扩展,其中内容脚本向后台脚本发送消息 chrome.runtime.sendMessage({greeting: "hello"}, function(response) { console.log(response.farewell); }); 当background.js接收到此消息时,它会得到具有 { ID, tab, url } 我想验证此消息是否由属于我的扩展名的内容脚本发送,而不是其他内容 如何验证发件人ID,background.js如何获取扩展I

我正在编写一个chrome扩展,其中内容脚本向后台脚本发送消息

chrome.runtime.sendMessage({greeting: "hello"}, function(response) {
  console.log(response.farewell);
});
当background.js接收到此消息时,它会得到具有

{ ID, tab, url }
我想验证此消息是否由属于我的扩展名的内容脚本发送,而不是其他内容

如何验证发件人ID,background.js如何获取扩展ID。

您不必这样做

有两个与消息相关的不同事件:

  • chrome.runtime.onMessage
    -它仅适用于您自己的分机发送的消息<代码>发件人用于确定上下文,即选项卡ID

  • chrome.runtime.onMessageExternal
    -它仅适用于其他来源发送的消息,无论是其他扩展还是网页。在那里,
    sender
    将包含相关页面的扩展ID或URL

    请注意,您可以在中的清单中显式限制外部消息的可能发件人。默认策略是不允许网页并允许所有扩展


  • 因此,为了总结,我必须在manifest.json中添加“external_connectable”:{“ids”:[],“matches”:[]},并确保我的javascript中只有onMessage调用,这样就没有人可以连接了。为了总结,如果不需要,就不要听
    onMessageExternal
    ,仅此而已。只有在你需要的时候才开始担心。