Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome extension: How to add a button to a page on a web site and add a click handler to it?

I am trying to dynamically add a button to a page on a third-party website, and add a click handler to the button, using a Chrome extension. I have read onClick within Chrome Extension not working, added the handler in a separate js file.

The problem is that Chrome tries to find that js file in the web server, not in the extension. So, 404 happens.

Let's say the web page is "http://www.somecompany.com/somepage.html". My extension code is like the following.

    var aButton = document.createElement('button');
    aButton.id = "aButton";
    thatDiv.appendChild(aButton);

    var aScript = document.createElement("script");
    aScript.src="aButtonHandler.js";
    thatDiv.appendChild(aScript);   

Chrome tries to load "http://www.somecompany.com/aButtonHandler.js", and of course the real web site does not have that script, so 404 happens. How can I add a button to a web site and execute alert("hello"); when the button is clicked?


Added

I added the code in aButtonHandler.js to the end of the content script itself, but nothing happened. What is wrong?

content script.js

addButton();

function addButton()
{
    //adds a button by the code above.
}

document.addEventListener('DOMContentLoaded', function() {
    var theButton = document.getElementById('aButton');
    theButton.addEventListener('click', function() {
        alert('damn');
    });
});

Added

This worked.

content script.js

addButton();

function addButton()
{
    //adds a button by the code above.
    aButton.addEventListener('click', function() {
        alert('damn');
    });
}
like image 731
Damn Vegetables Avatar asked Aug 25 '17 16:08

Damn Vegetables


1 Answers

Using the setInterval function to check <button> element is exists, if not create and append the <button> element.

var myVar = setInterval(function() { 
    if(document.getElementById('aButton')) {
        //  clearInterval(myVar);
        return false;
    } else {
        if(document.getElementsByClassName("assignedToUsers")[0]) {
            var button = document.createElement("button");
            button.innerHTML = "Test";
            button.id = "aButton";
            button.type = "button";
            document.getElementsByClassName("assignedToUsers")[0].appendChild(button);

            var theButton = document.getElementById('aButton');
            theButton.addEventListener('click', function() {
                console.log(document.getElementsByClassName("ms-TextField-field")[0].value);
            });
        }
    }
}, 500);
like image 82
Gtm Avatar answered Sep 21 '22 13:09

Gtm