通过chrome.runtime.sendMessage()传递的消息?

时间:2014-03-23 10:28:23

标签: javascript google-chrome dom google-chrome-extension message-passing

我提到了chrome文档https://developer.chrome.com/apps/runtime#type-MessageSender以及https://developer.chrome.com/apps/runtime#event-onMessage

在我的示例Chrome扩展程序中,我想将 contentscript.js 中的数字传递给 popup.js

contentscript.js:

var fromDOM = 100;
chrome.runtime.sendMessage({fromDOM});//here I'm passing value in fromDOM 

popup.js:

chrome.runtime.onMessage.addListener(function(response){

  number = response; //here I'm assigning value in response to total

  document.getElementById("output").innerHTML=number;//manipulating an element
                                                    // in popup.html
}
);

元素“输出”未被修改。

那么,我做得对吗? “任何消息”参数应该如何,我可以这样使用该参数吗?

更新了我的contenscript.js和background.js:

contenscript.js:

//code to get values from a table in results page
var table = document.getElementsByClassName("collapse")[0];

var marks = new Array();

 for(var i=0;i<8;i++)
   marks[i] = table.children[0].children[i+1].children[5].innerHTML;

 var total=0;
 for(var i=0;i<8;i++)
   total += Number(marks[i]);


var fromDOM = total;
chrome.runtime.sendMessage(fromDOM);

background.js:

//code to display pageaction button on domain results.griet.in
chrome.runtime.onInstalled.addListener(function() {
    chrome.declarativeContent.onPageChanged.removeRules(undefined, function() {
        chrome.declarativeContent.onPageChanged.addRules([{
            conditions: [
                new chrome.declarativeContent.PageStateMatcher({
                    pageUrl: {
                        hostSuffix:<website>
                    }
                })
            ],
            actions: [new chrome.declarativeContent.ShowPageAction()]
        }]);
    });
});

//code to inject contentscript.
chrome.tabs.executeScript({"file": "contentscript.js"});

0 个答案:

没有答案