Damn Vegetables
Damn Vegetables

Reputation: 12464

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');
    });
}

Upvotes: 8

Views: 9562

Answers (1)

Gtm
Gtm

Reputation: 263

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);

Upvotes: 1

Related Questions