Call a function in background from popup

那年仲夏 提交于 2019-12-03 08:21:52

问题


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.


回答1:


Try this

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



回答2:


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();
    }
);



回答3:


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.




回答4:


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



来源:https://stackoverflow.com/questions/5443202/call-a-function-in-background-from-popup

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