无法将儿童附加到Chrome扩展程序的页面

时间:2014-02-01 20:08:41

标签: javascript google-chrome dom google-chrome-extension appendchild

这是简化的代码,它在appendChild行之后停止工作:

$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();
});

知道我缺少什么吗?

我也尝试过:

chrome.extension.getBackgroundPage().appendChild()

几乎相同的结果

- 编辑 -

使用content scripts

工作(带字符串):

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

但是

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

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

无法使用,如何将节点传递给code参数?

感谢

2 个答案:

答案 0 :(得分:2)

您要将html方法的返回值指定给divNode

正如您在jQuery documentation上找到的那样,用作setter的html方法返回jQuery对象以允许链式调用。

因此,您尝试将jQuery对象附加到DOM节点,该节点无效。

你要做的是:

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

或其他:

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

答案 1 :(得分:1)

如果发布的JS在内容脚本中运行,则不需要jQuery domload事件。内容脚本通常在加载dom时运行。 (您可以在清单中更改,但不应该。)

如果没有jQuery,您的init()将如下所示:

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

您可以在脚本底部运行init(),而不是在事件处理程序中运行。

如果它作为内容脚本运行,则不需要背景页面或executeScript()

您的原始代码有一个jQuery错误btw:document.body.find不是一个函数。