Call a function in background from popup

99封情书 提交于 2019-12-02 22:16:28

Try this

 var bgPage = chrome.extension.getBackgroundPage();
 var dat =  bgPage.paste(); // Here paste() is a function that returns value.

It is indeed possible, using Message Passing.

popup.js

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

background.js

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

chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse){
        if(request.msg == "startFunc") func();
    }
);

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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!