从后台传递消息到内容脚本

时间:2013-09-21 11:22:11

标签: google-chrome-extension tabs sendmessage

在我的扩展程序中,我使用background.js将消息从content.js传递到chrome.tabs.sendMessage。对于有效的tabId(我打印其值,非负值),有时内容会在background.js中的警报之后打印警报,但不是大多数时间。这是示例代码。我在代码中遗漏了什么吗?我希望,每次在background.js中显示提醒时,content.js都必须有提醒。我正在处理请求并且页面尚未完全显示时发送消息。

background.js

...

if(url == "http://example.com"){
   alert("In background");
   chrome.tabs.sendMessage(tabId, {msg: "HELLO"});          
}

...

content.js

chrome.runtime.onMessage.addListener(
        function (request, sender, sendResponse) {    
          alert("In content");
        });

的manifest.json

  "content_scripts": [  
        {
            "matches": [
                "http://*/*",
                "https://*/*"
            ],
            "js": ["content.js"],
            "all_frames": true,
            "run_at": "document_end"
        }
    ],

已添加

只是提醒您,我想在第一次请求后将DOM中的图像URL更改为http(从http强制重定向到http),重定向到onBeforeRquest中的https,失败。这不起作用,因为我意识到内容脚本没有收到所有消息。作为以下代码中的简单测试,我希望每次打印消息“In onError20ccurred”时,它必须在控制台后面跟着“In content”,但它不能以这种方式工作。欢迎任何建议。我首先确认内容是否准备就绪,然后发送消息。这是代码:

content.js:

chrome.extension.sendRequest({contentStatus: "activated"});

chrome.runtime.onMessage.addListener(
   function (request, sender, sendResponse) {
      console.log(request.srcurl);  //or console.log("In content");
});

background.js:

var contentActive = {}  
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {   
   chrome.tabs.getSelected(null, function(tabs) {       
      if (request.contentStatus == "activated")
          contentActive[tabs.id] = true;    
   });    
});

chrome.webRequest.onErrorOccurred.addListener(
   function(details){ 
      if(details.type == 'image' && details.url == "https://example.com/image1.jpg") {     
         if(contentActive[details.tabId]){
           console.log("In onErrorOccurred");
              chrome.tabs.sendMessage(details.tabId, {srcurl: "In content"});       
        }
     }
}, {urls: ['https://*/*']});

0 个答案:

没有答案
相关问题