小编use*_*206的帖子

将消息从后台脚本发送到内容脚本,然后发送到注入的脚本

我正在尝试将消息从后台页面发送到内容脚本,然后将该内容脚本中的消息发送到注入的脚本.我试过这个,但它没有用.

这是我的代码的样子.

的manifest.json

{
  "manifest_version": 2,

  "name": "NAME",
  "description": ":D",
  "version": "0.0",
  "permissions": [
    "tabs","<all_urls>"
  ],
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["content_script.js"]
    }
  ],
  "web_accessible_resources": [
      "injected.js"
  ],
  "background":{
      "scripts":["background.js"]
  }
}
Run Code Online (Sandbox Code Playgroud)

background.js

chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
  chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, function(response){});
});
Run Code Online (Sandbox Code Playgroud)

content_script.js

var s = document.createElement('script');
s.src = chrome.extension.getURL('injected.js');
s.onload = function(){ 
        this.parentNode.removeChild(this);
};
(document.head||document.documentElement).appendChild(s);


chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    document.dispatchEvent(new CustomEvent('Buffer2Remote', {todo: "LOL"}));
});
Run Code Online (Sandbox Code Playgroud)

injected.js

document.addEventListener('Buffer2Remote', function(e){
    alert(e.todo);
});
Run Code Online (Sandbox Code Playgroud)

消息发送在第一部分background - > content_script中不起作用.我的代码有什么问题吗?

javascript google-chrome-extension

12
推荐指数
1
解决办法
1万
查看次数