user1176420
user1176420

Reputation: 123

JavaScript injection in chrome extension

I'm new with 'chrome extension development', and I wanted to make a extension.
That extension has to inject code in a web page when the user clicks a button on the popup-page. I saw different subjects about that, but it doesn't seem to be possible to inject code that 'interacts' with the existing code of the web page. For example: a variable called test is made when the user opens a web page, I want to get that variable and use it in my code (for example: alert(test);). I tried several ways to achieve this, but it won't work. How can I do this? I tried:

chrome.tabs.executeScript(null,{code:"alert('test')"}); 
console.log("alert('test');");

This worked, but only for the popup page and so the variable 'test' didn't exist.

Upvotes: 2

Views: 3382

Answers (2)

user1176420
user1176420

Reputation: 123

Thanks, it's working now, here is my code:

Popup:

function makeRequest(act){
chrome.tabs.getSelected(null, function(tab) {
    chrome.tabs.sendRequest(tab.id, {action: act, tabid: tab.id}, function(response) { });
});}
//inputs:
<input type="button" id="addDiv" value="Add Div" onClick="makeRequest(this.id);" />
<input type="button" id="addButton" value="Add button" onClick="makeRequest(this.id);" />

contentScript:

function injectCode(text) {
    var script = document.createElement("script");
    var parent = document.documentElement;
    script.text = text;
    script.setAttribute("id", "codeInjection");
    script.setAttribute("extension", "Chrome");
    parent.appendChild(script);
    parent.removeChild(script);
}
var codes = Array();
codes["addDiv"] = "alert('Add a div');";
codes["addButton"] = "alert('Add a button');";
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
    switch (request.action) {
        case "addDiv":
            injectCode(codes["addDiv"]);
            break;
        case "addButton":
            injectCode(codes["addButton"]);
    }
});

Upvotes: 2

ronme
ronme

Reputation: 1172

Your perception is very true. Chrome extension code cannot interact directly with the existing page's code - they run in different, secluded environments. What they do share, though, is the DOM structure and (HTML5) localStorage, so you can use one of those to pass messages to each other, e.g. by defining listeners for DOM changes.

Upvotes: 1

Related Questions