简体   繁体   中英

How can a Chrome extension respond to a button click in a page?

I'm making a first attempt at writing a Chrome extension and I want it to respond to a button click which resembles the facebook like button, G+ button, etc. This means that I'd like the extension to work on any page, but only respond to a button with a particular ID or something, which seems tricky with the "permission" and/or "matches" item of the JSON manifest.

Since I'm unfamiliar with extensions, should I have the button have its own javascript function which calls/activates the extension somehow, or should I have the extension have an event listener (would this be in a content script?) which listens for a particular button click event?

Note: I took a look at this question but the extension in that case was for a specific web page, so I'm not convinced that the answer will work for me.

First thing you want is that your extension should work on all pages, so include your content script in manifest as follows :

"content_scripts": [
    {
        "matches": [
            "<all_urls>"
        ],
        "js": [
            "jquery.js",
            "myscript.js"
        ]
    }

This will inject myscript.js in every page. Now just check if your desired button is present or not. eg :

if(document.getElementById('gplus') != null) {
   // Add your implementation.
   var g = document.getElementById('gplus');
   g.click = funct;
}

Now define function funct() according to yourself.

try using content scripts. They act like they are part of the page. if i had a document.getelementbyid("#hi").onclick=function(){}; and someone clicked a button with an id of "hi" inside the current page, the event would fire.

Read more at: https://developer.chrome.com/extensions/content_scripts

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM