2

私が見た例はタブから拡張機能までであり、その逆ではないので、ここで少し助けを探しています。

カスタムChrome拡張機能でデバッグしているページ/タブのソースコードを取得しようとしています。拡張機能がメッセージを呼び出し、応答が呼び出しを行う拡張機能パネルのjavascriptに返送されるようにします。

マニフェスト

"permissions": [
  "tabs",
  "<all_urls>",
  "debugger"
],
"background": {
  "scripts": ["background.js"],
  "persistent": false
},
"content_scripts": [
  {
  "matches": ["<all_urls>"],
  "js": ["content.js"]
  }
],

background.js

chrome.browserAction.onClicked.addListener(function() {
  chrome.tabs.query({active:true, windowId:chrome.windows.WINDOW_ID_CURRENT}, function(tabs) {
    debuggee = {tabId:tabs[0].id};
chrome.debugger.attach(debuggee, version, onAttach.bind(null, tabs[0].id));
  });
});

function onAttach(tabId) {
  chrome.windows.create({url: "spy.html?" + tabId, type: "panel", width: 900, height: 700}, function(window) {
    winId = window.id;
});

content.js

chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
  if (request.data == "getHTML") {
      sendResponse({data: document.getElementById('header').innerHTML});
  }
});

spy.html

<script src="spy.js" type="text/javascript"></script>

spy.js

window.addEventListener("load", function() {
  chrome.debugger.sendCommand({tabId:tabId}, "DOM.getDocument");
  chrome.debugger.onEvent.addListener(onEvent);
});

function onEvent(debuggeeId, message, params) {    
  if (message=="DOM.documentUpdated") {
    chrome.tabs.sendMessage(tabId, {data: "getHTML"}, function(response) {console.log(response.data);});
  }

結果

ポートエラー:接続を確立できませんでした。受信側は存在しません。miscellaneous_bindings:235 chromeHidden.Port.dispatchOnDisconnect miscellaneous_bindings:235

'undefined'のイベントハンドラーのエラー:未定義のプロパティ'data'を読み取れませんTypeError:
chrome-extension://fpdkndicjblnkakkiiapbbdflkehjmgm/headers.js:132:91
at miscellaneous_bindings:279:11
でundefinedのプロパティ'data'を読み取れませんchrome.Event.dispatchToListener(event_bindings:387:21)
at chrome.Event.dispatch_(event_bindings:373:27)
at chrome.Event.dispatch(event_bindings:393:17)
at Object.chromeHidden.Port.dispatchOnDisconnect(miscellaneous_bindings:238 :27)

実行しようとすると、このエラーが発生します。私は何が欠けていますか?

4

2 に答える 2

1

OK私はそれを理解しました。ロードされたページのDOMが必要なので、バックグラウンドページでchrome.tabs.onUpdated.addListenerを使用して、ページがロードされたときにコードを送信します。このように、タブと拡張機能の間の双方向通信に依存する必要はありません。

マニフェスト

content.jsを削除しました

background.js

以下を追加しました

chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
  if (tabId != _tabId) {return;}
  if (changeInfo.status == "complete") {
    chrome.tabs.executeScript(tabId, {code:"var x = document.documentElement.innerHTML;x"}, function (r) {
      chrome.extension.sendMessage(null, {"data": r[0]});       
    });
  }
});

content.js

削除されました

spy.js

以下を追加しました

chrome.extension.onMessage.addListener(function(request, sender) {
  console.log("Request.data: " + request.data);
});
于 2013-01-09T21:41:07.920 に答える
1

これを確認するためのメッセージを渡すためのサンプルコードを探している場合、問題をデバッグするための完全なスクリプトを投稿できますtabIdか?chrome.tabs.sendMessage(tabId,Chrome ExtensionDebugging Tab

参考文献

マニフェスト.json

登録popupページとcontent scripts

{
 "name": "Pass message from Chrome Extension to Debugging Tab",
 "version": "1",
 "description": "http://stackoverflow.com/questions/14205155/how-can-i-pass-a-message-from-my-chrome-extension-to-debugging-tab",
 "browser_action": {
   "default_title": "Selected Text",
   "default_popup": "popup.html" 
 },
 "permissions": [
   "tabs",
   "<all_urls>"
 ],
 "content_scripts": [
  {
    "matches": ["<all_urls>"],
    "js": ["selection.js"]
  }
 ],
 "manifest_version": 2
}

popup.html

HTMLがCSPに準拠していることを確認

<!DOCTYPE html>
<html>

    <head>
        <style>
            body {
                width: 300px;
            }
            textarea {
                width: 250px;
                height: 100px;
            }
        </style>
        <script src="popup.js"></script>
    </head>

    <body>
          <button id="submit">Pass Message</button>
    </body>

</html>

popup.js

メッセージをコンテンツスクリプトに渡します。

function passMessage() {
    //Select current tab to send message
  chrome.tabs.query({"active":true,"currentWindow":true,"status":"complete","windowType":"normal"}, function(tabs) {
  //It returns array so looping over tabs result
    for(tab in tabs){

    //Send Message to a tab
    chrome.tabs.sendMessage(tabs[tab].id, {method: "Hi Content Script"});
    }   
});
}


// Bind On click event to passMessage() function
document.addEventListener("DOMContentLoaded",function (){

    document.getElementById("submit").onclick = passMessage;
});

selection.js

ポップアップページから送信されたメッセージをキャッチするハンドラーを追加しました

 //Add a handler to handle message sent from popup.html
 chrome.extension.onMessage.addListener(function(request, sender) {
    console.log("Message "+request+" is recieved");

});

編集:

次のような非推奨のAPI()を削除した後、コードを機能させましたsendResponse

background.js

chrome.browserAction.onClicked.addListener(function () {
    version = "1.0";
    chrome.tabs.query({
        active: true,
        windowId: chrome.windows.WINDOW_ID_CURRENT
    }, function (tabs) {
        debuggee = {
            tabId: tabs[0].id
        };
        chrome.debugger.attach(debuggee, version, onAttach.bind(null, tabs[0].id));
    });
});

function onAttach(tabId) {
    chrome.windows.create({
        url: "spy.html?" + tabId,
        type: "panel",
        width: 900,
        height: 700
    }, function (window) {
        winId = window.id;
    });
}

content.js

chrome.extension.onMessage.addListener(function (request, sender) {
    console.log("Message recieved");
    if (request.data == "getHTML") {
        chrome.extension.sendMessage({
            "data": "Some Stuff"
        });
    }
});

spy.js

tabId = parseInt(window.location.search.substring(1));
window.addEventListener("load", function () {

    chrome.debugger.sendCommand({
        tabId: tabId
    }, "DOM.getDocument");
    chrome.debugger.onEvent.addListener(onEvent);
});

function onEvent(debuggeeId, message, params) {
    if (message == "DOM.documentUpdated") {
        chrome.tabs.sendMessage(tabId, {
            "data": "getHTML"
        });
    }
}
chrome.extension.onMessage.addListener(function (response, sender) {
    console.log(response);
});

ただし、テスト中に開発者ツールを手動でトリガーしないようにしてください。

于 2013-01-08T05:52:41.927 に答える