Toni Michel Caubet
Toni Michel Caubet

Reputation: 20183

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?

Upvotes: 4

Views: 3553

Answers (2)

Rudie
Rudie

Reputation: 53890

If the posted JS runs in a content script, you don't need the jQuery domload event. Content scripts are run usually when the dom has loaded. (You can change that in the manifest, but you shouldn't.)

Without jQuery, your init() would look like this:

// Create div
var divNode = document.createElement('div');
divNode.id = 'layoutVsDesign';
divNode.innerHTML = 'test';

// Append to open page doc
document.body.appendChild(divNode);

var thatDiv = document.querySelector('#layoutVsDesign');
alert(thatDiv);
this.designPreviewer = thatDiv;

You can run that init() at the bottom of the script, not inside an event handler.

If it runs as a content script, there's no need for background pages or executeScript().

Your original code had a jQuery error btw: document.body.find wouldn't be a function.

Upvotes: 1

Andrea Parodi
Andrea Parodi

Reputation: 5614

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

Upvotes: 2

Related Questions