如何发送json并在chrome.runtime.sendMessage中调用函数?

时间:2015-06-11 08:28:09

标签: javascript google-chrome-extension

在我的contentscript.js中我有这个:

chrome.extension.sendMessage({ action: "isBlacklist", url: tablink, title: title });

这是我的background.js

chrome.runtime.onMessage.addListener(function(request) {
  if(request.action== "isBlacklist") {
    console.log("url: ", request.url);
    console.log("title: ", request.title);
   }
}

但我想这样写,我不知道怎么写chrome扩展名:

var data={"url":url,"title":title};
chrome.extension.sendMessage({ action: "isBlacklist",data:data});

并在后台:

chrome.runtime.onMessage.addListener(function(request) {
   //I don't know how to write but this is a example 
   //var fn = null;
    //if(typeof request.action === 'function'){
     // fn = request.action;
   //}
 }

然后我可以调用一个函数:

function isBlacklist(data){
   console.log("url: ", data.url);
   console.log("title: ", data.title);
}
//another function if we send message more in contentscript.js.

因此,如果我们可以这样写,我们可以调用多功能而不是像这样:

   if(request.action== "action1") {
     method1();
  }
 else if(request.action== "action2") {
     method2();
 }

1 个答案:

答案 0 :(得分:0)

您可以在对象中拥有所有功能:

<强> background.js

var Actions = {
    isBlacklist: function(){
        //A good way to use data, `this` is equivalent to `data`
        console.log("from content script...", this);
        console.log("url: ", this.url);
        return false
    },
    isBatman: function(){
        console.log("from content script...", this);
        console.log("url: ", this.url);
        return "I am Batman"
    }
};

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if(typeof Actions[request.action] === "function"){
        sendResponse(Actions[request.action].call(request.data));
    }
});

<强> contentScript.js

var data = {"url": "google.com", "title": "The title"};
chrome.extension.sendMessage({action: "isBatman", data: data}, function(value){
    console.log("From background.js ->", value)
});