Executing Chrome extension onclick instead of page load

后端 未结 2 690
半阙折子戏
半阙折子戏 2021-01-31 00:32

I created a Chrome extension that works as expected except that it only executes when I load a page that matches the conditions in the manifest. I have tried for hours to make i

相关标签:
2条回答
  • 2021-01-31 00:37

    use browserAction API ,see here

    the onClick events may help you. also see these exsamples from google :

    0 讨论(0)
  • 2021-01-31 00:46

    As i see you want to run code when

    • User has clicked on Browser Action ICON and
    • URL pattern is a match

    If so, you have use Background pages in conjunction with Tabs API.

    Demonstration

    This is a sample demonstration of your use case and you can put all your code and assign permissions for all match URL(s).

    manifest.json

    Registered Background Page, Browser Action and Permissions for Target Pages.

    {
            "name": "Get Response URL",
            "version": "1.0",
            "manifest_version": 2,
            "browser_action": {
            "name": "Click to get URL"
            },
            "background":{
                "scripts":["background.js"]
            },
            "permissions":["https://www.google.co.in/*"] //Put All your URL here
     }
    

    background.js

    Put all Your Target Matching URL in a series of if conditions here

    chrome.browserAction.onClicked.addListener(function (tab) { //Fired when User Clicks ICON
        if (tab.url.indexOf("https://www.google.co.in/") != -1) { // Inspect whether the place where user clicked matches with our list of URL
            chrome.tabs.executeScript(tab.id, {
                "file": "contentscript.js"
            }, function () { // Execute your code
                console.log("Script Executed .. "); // Notification on Completion
            });
        }
    });
    

    contentscript.js

    alert("Code Executed ... ");
    

    Output

    When you browse to https://www.google.co.in/ and after click of browser action you see Alert in the page.

    References

    • Tabs API
    • Background Pages
    0 讨论(0)
提交回复
热议问题