Call a function in background from popup

2019-03-16 00:35发布

Is there a way to call a function in the background script from the popup? I can't explain it much further than that question. It's not an error I'm having with what I'm trying to do but rather something I completely don't know how to do. I want to make it possible to click a button in the popup page that'll call a function defined in the background page.

4条回答
我欲成王,谁敢阻挡
2楼-- · 2019-03-16 01:10

It is indeed possible, using Message Passing.

popup.js

$("#button").click(function(){
    chrome.extension.sendMessage({ msg: "startFunc" });
});

background.js

var func = function(){
    alert("Success!");
};

chrome.extension.onMessage.addListener(
    function(request, sender, sendResponse){
        if(request.msg == "startFunc") func();
    }
);
查看更多
兄弟一词,经得起流年.
3楼-- · 2019-03-16 01:14

Try this

 var bgPage = chrome.extension.getBackgroundPage();
 var dat =  bgPage.paste(); // Here paste() is a function that returns value.
查看更多
The star\"
4楼-- · 2019-03-16 01:16

You can still use chrome.extension.sendMessage. But that is getting deprecated. Use chrome.runtime.sendMessage and chrome.runtime.onMessage.addListener instead.

查看更多
混吃等死
5楼-- · 2019-03-16 01:24

You can just call background.js functions in popup.js. You don't need to do anything extra. At least that is the case for me.

Edit: you probably need to add

"background": { "scripts": "background.js" }

in your manifest.json file.

查看更多
登录 后发表回答