Manipulate DOM in chrome extension

11,211

If you want to play with browser tab DOM on event of popup. In this case you have to pass a message to content script from background script, or inject JavaScript into content script : have a look

manifest.json

{
    "name": "First",
    "version": "1.0",
    "manifest_version": 2,
    "description": "First extension",
    "background": {
        "scripts": ["test.js"]
    },    
    "page_action": {
        "default_icon": "icon.png",
        "default_popup": "popup.html"
    },    
    "content_scripts": [ {
        "js": [ "jquery.min.js", "content_script.js"  ],
        "matches": [ "http://*/*", "https://*/*" ]    
    } ],

    "permissions" : [
        "tabs",
        "http://*/*"
            ]
}

content_script.js

function myfunc(){
    var x = $('#options option:selected').text();
    $("body").append('<div style="width:200px; height:200px; border: 1px solid red;"></div>');
}

$(document).ready(myfunc);

Now you will get A box with red border at the bottom of the page.

popup.js

function myfunc(){
    var x = $('#options option:selected').text();
    chrome.extension.sendMessage({sel_text: x});
}

$(document).ready(function(){
    $('#options').change(myfunc);
});

test.js (used in background)

chrome.extension.onMessage.addListener(
  function(request, sender, sendResponse) {
    appendTextToBody(request.sel_text);
  });

function appendTextToBody(text) {
  chrome.tabs.getSelected(null, function(tab) {
    chrome.tabs.executeScript(tab.id, {"code" : '$("body").append("Test : "'+text+');'}) ;
  });
}

function check(tab_id, data, tab){
    if(tab.url.indexOf("google") > -1){
        chrome.pageAction.show(tab_id);
    }
};
chrome.tabs.onUpdated.addListener(check);
Share:
11,211
RanRag
Author by

RanRag

I am an undergraduate student who has completed his B-Tech in Information &amp; Communication Technology(ICT), INDIA. I am just a normal guy who has recently found interest in programming. Initially I was a big Java fan but now I am a Python enthusiast. Currently, exploring Android App Development.

Updated on June 04, 2022

Comments

  • RanRag
    RanRag almost 2 years

    I am trying to learn about chrome extensions but I am not able to understand how to manipulate DOM of a page using content_scripts.

    manifest.json

    {
        "name": "First",
        "version": "1.0",
        "manifest_version": 2,
        "description": "First extension",
        "background": {
            "scripts": ["test.js"]
        },
    
        "page_action": {
    
            "default_icon": "icon.png",
            "default_popup": "popup.html"
        },
    
        "content_scripts": [ {
            "js": [ "jquery.min.js", "popup1.js"  ],
            "matches": [ "http://*/*", "https://*/*" ]
    
        } ],
    
        "permissions" : [
            "tabs",
            "http://*/*"
                ]
    }
    

    test.js

    function check(tab_id, data, tab){
    
        if(tab.url.indexOf("google") > -1){
            chrome.pageAction.show(tab_id);
                }
    
    };
    chrome.tabs.onUpdated.addListener(check);
    

    popup1.js

    function myfunc(){
    
        var x = $('#options option:selected').text();
        $("body").append('Test');
        alert(x);
        //window.close();
    
    }
    
    $(document).ready(function(){
    
        $('#options').change(myfunc);
    
    });
    

    The above code/extension works fine because myfunc gets called but it doesn't inject Test into the body of google.com.

    So, where am I going wrong in accessing/manipulating the DOM.

  • RanRag
    RanRag over 11 years
    Your code works fine. But I need to add an event listener to look for change in drop-down list selected value. Therefore as soon as I add $(document).ready(function(){ $('#options').change(myfunc); }); keeping rest all the same the above code doesn't work.
  • Raghvendra Parashar
    Raghvendra Parashar over 11 years
    I have updated my answer, take a look and tell me, if there is something wrong .. thanks
  • RanRag
    RanRag over 11 years
    Thanks for the updated code. I tried but it is still not appending anything to the page html. I tried debugging and found that appendTextToBody is getting called and the value of text is also as required but chrome.tabs.executeScript(tab.id, {"code" : '$("body").append("Test : "'+text+');'}) ;is not working as required.
  • Raghvendra Parashar
    Raghvendra Parashar over 11 years
    may be there JQuery is not exist, try this one : chrome.tabs.executeScript(tab.id, {"code" : 'var my_span = document.createElement('span'); my_span.innerHTML("Test : "); document.body.appendChild(my_span)'}); instead of $("body").append("Test : "'+text+');
  • RanRag
    RanRag over 11 years
    Now, this is really strange I tried the simplest of code chrome.tabs.executeScript(tab.id, {"code" : "alert('hello')"}) ; and it is not working. It is late night now, so I will give it a try again in the morning and get back to you. Thanks for your help.
  • RanRag
    RanRag over 11 years
    @Noob: If u see that by default google now uses https. So, try adding "https://*/" in permissions inside manifest.json.