在chrome扩展中操作DOM

时间:2012-12-29 14:10:32

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

我正在尝试了解Chrome扩展程序,但我无法理解如何使用DOM操纵页面的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);

});

上述代码/扩展程序运行正常,因为myfunc被调用但它没有Test注入google.com的主体。

所以,我在访问/操作DOM时出错了。

1 个答案:

答案 0 :(得分:8)

如果要在弹出事件中使用浏览器选项卡DOM。在这种情况下,您必须将消息从content script传递到background script,或inject JavaScript传递给content script:看看

的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);

现在,您将在页面底部看到A box with red border

<强> popup.js

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

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

test.js(在后台使用)

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