Chrome extension development: Call a method in popup from background_html

时光毁灭记忆、已成空白 提交于 2019-12-12 02:25:51

问题


I have a popup named mf_popup.html and my background page is named mf_background.html.

As I start the browser my background page fires (as is my understanding, I am new to Chrome development), and I would like to call a function in my mf_popup.html page from my background page.

For example:

Start chrome

background page fires

background page calls some function in popup page (which initiates some stuff)

How do I do the above?


回答1:


if you place the needed code in both html-files in mf_javascript.js and includes the script in both with this line:

<script type="text/javascript" src="mf_javascript.js">



回答2:


mf_popup.html

//sendRequest([any type] request, [function] responseCallback)
chrome.extension.sendRequest({
    function: "foo", 
    params: [myParam1, myParam2],
    function(response) {
      alert("foo returns:"+response.result+");
    }
});

mf_background.html

chrome.extension.onRequest.addListener(
    function(request, sender, sendResponse) {
        if(request.function == "foo") 
            var bar = foo(request.params[0], request.params[1]);
        sendResponse({result: bar});
    }
);

You also could just use sendRequest("foo") if you don't want send any params and/or use an callback function.



来源:https://stackoverflow.com/questions/5913580/chrome-extension-development-call-a-method-in-popup-from-background-html

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