Call a function in background from popup
Is there a way to call a func开发者_运维技巧tion 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.
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.
精彩评论