Search code examples
javascriptgoogle-chromedomgoogle-chrome-extensionappendchild

Can't append a child to page from a Chrome extension


This is the simplified code, it's stops working after the appendChild line:

$preview = {
    designImg: '',
    thePage: null,
    designPreviewer: null,
    init: function(){
        var divNode = $('<div>').attr('id','layoutVsDesign').html('test');
        document.body.appendChild( divNode );
        alert('I never happen');
        this.designPreviewer = document.body.find('#designPreviewer');
    }
};

$(document).ready(function(){
    $preview.init();
});

Any idea what I am missing?

I also tried:

chrome.extension.getBackgroundPage().appendChild()

With pretty much the same result

-EDIT-

Using content scripts:

works (takes a string):

chrome.tabs.executeScript({
   code: 'document.body.style.display = "none"'
});

But

chrome.tabs.executeScript({
   code: 'document.body.appendChild("<div>tttttttesttt</div>")'
});

or

chrome.tabs.executeScript({
   code: 'document.body.appendChild(node[0])'
});

Won't work, how can I pass the node to the code parameter?


Solution

  • You are assigning the return value of html method to divNode

    As you can find on jQuery documentation, html method used as a setter return the jQuery object to allow for chained calls.

    So, you are trying to append a jQuery object to a DOM node, which is not valid.

    What you have to do is:

    var divNode = $('<div>').attr('id','layoutVsDesign').html('test');        
    $("body").append( divNode ); //append a jQuery object using jQuery method
    

    or otherwise:

    var divNode = $('<div>').attr('id','layoutVsDesign').html('test');        
    document.body.appendChild( divNode[0] ); //append a DOM node with DOM method