Run script each time Chrome extension icon clicked

前端 未结 5 1199
有刺的猬
有刺的猬 2020-12-02 06:44

How do I write a chrome extension such that every time a user clicks the icon, my script is run but no popup is opened? (I would look this up in the docs myself but for wha

5条回答
  •  庸人自扰
    2020-12-02 07:09

    you need to add a background file. but firstly ou need to add an attribute in manifest.json like,

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

    now name a file in your extension folder as background.js there is a way of sending objects from background to your content scripts suppose your content script is named content.js then what you need to do is write this code snippet in background.js file

    chrome.browserAction.onClicked.addListener(sendfunc);
    function sendfunc(tab){
        msg={txtt:"execute"};
        chrome.tabs.sendMessage(tab.id,msg);
    }
    

    what the above code is doing is sending an object named msg to content page and this msg object has a property txtt which is equal to "execute". what you need to do next is compare the values in content script as

    chrome.runtime.onMessage.addListener(recievefunc);
    function receivefunc(mssg,sender,sendResponse){
        if(mssg.txtt==="execute"){
          /*  
             your code of content script goes here
          */
        }
    }
    

    now whenever you click the extension icon an object named msg is sent from background to content. the function "recievefunc()" will compare its txtt property with string "execute" if it matches your rest of the code will run.

    note: msg,txtt,sendfunc,receivefunc,mssg all are variables and not chrome keywords so you can use anything you want.

    hope it helps.

    :)

提交回复
热议问题