chrome.runtime.onMessage.addListener不在内容脚本中工作

时间:2016-08-17 14:02:38

标签: javascript

在chrome扩展程序中,我尝试从后台脚本向内容脚本发送消息。我没有在内容脚本中收到消息。哪里出错了?这是background.js

function createAlarm() {
   chrome.alarms.create('bookcab', {
          periodInMinutes: 1
   });
}

chrome.alarms.onAlarm.addListener(function(alarm) {
    if (alarm.name === 'bookcab') {
       var url = 'http://cab/';
       chrome.tabs.create({ url:url, active: true });
       chrome.tabs.query({active:true}, function(tabs){
          chrome.tabs.sendMessage(tabs[0].id, {"message": "sample_msg"});
        });
    }
});

createAlarm();

content_script.js具有以下代码,

chrome.runtime.onMessage.addListener(
  function(request,sender,sendresponse) {
    if( request.message === "sample_msg" ) {
       console.log('message from content script');                     
    }
  }
);

如果重要的话,这里是manifest.json

{
    "manifest_version": 2,
    "name":"bookcab",
    "version":"0.1",
    "background": {
        "scripts":["background.js"]
    },
    "permissions": [
        "alarms",
        "tabs"
    ],
    "content_scripts": [{
        "matches":["<all_urls>"],
        "js": ["content_script.js"],
        "run_at" : "document_end"
    }]
}

1 个答案:

答案 0 :(得分:1)

在向内容脚本发送消息之前,我已经包含了一个标签加载完成。

等待TAB完全加载

chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {          
   if (changeInfo.status == 'complete') {   
      chrome.tabs.query({active: true}, function(tabs){
         chrome.tabs.sendMessage(tabs[0].id, {"message": "sample_msg"});
      }
   }
});