How to show Chrome Extension on certain domains?

前端 未结 3 1583
悲&欢浪女
悲&欢浪女 2020-12-06 11:42

I\'m writing my first Chrome Extension. I\'ve used permission, but I\'m seeing my button everywhere.

How can I only show the button on the addresses I\'m writing th

3条回答
  •  感动是毒
    2020-12-06 12:19

    Create background.js which checks for updated and highlighted tab.

    function checkForValidUrl(tabId, changeInfo, tab) {
    
       // If  'example.com' is the hostname for the tabs url.
       var a = document.createElement ('a');
       a.href = tab.url;
       if (a.hostname == "example.com") {
           // ... show the page action.
           chrome.pageAction.show(tabId);
       }
    };
    
    // Listen for any changes to the URL of any tab.
    chrome.tabs.onUpdated.addListener(checkForValidUrl);
    //For highlighted tab as well
    chrome.tabs.onHighlighted.addListener(checkForValidUrl);
    

    Create popup.html and popup.js in the similar manner.

    You can use the variables defined in background.js in content scripts (popup.js) with chrome.extension.getBackgroundPage().variableName

    Here's the example extention download link.

    For your reference and ease, here's the sample manifest.json file

     {
        "manifest_version": 2,
        "name": "Example Extension",
        "version": "1.0",
    
        "background": {
            "scripts": ["background.js"]
        },
    
        "page_action":{
            "default_icon": "images/icon_16.png",
            "default_popup": "popup.html",
            "default_title": "Title for the extension"
        },
        "permissions": [
            "tabs"
        ]
    }
    

提交回复
热议问题