2

Chrome拡張機能について学習しようとしていDOMますが、を使用してページを操作する方法を理解できませんcontent_scripts

マニフェスト.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挿入されません。Testgoogle.com

それで、DOMへのアクセス/操作でどこが間違っているのでしょうか。

4

1 に答える 1

10

ポップアップのイベントでブラウザタブDOMを操作したい場合。この場合、content scriptからbackground script、またはinject JavaScriptにメッセージを渡す必要がありますcontent script:見てください

マニフェスト.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);
于 2012-12-29T17:21:54.763 に答える