如何从调试选项卡到扩展脚本获取DOM

时间:2013-01-07 22:25:32

标签: google-chrome-extension

我在这里寻求一些帮助,因为我看到的例子只是从标签到扩展名,而不是相反。

我正在寻找使用自定义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:无法读取未定义的属性'data'
      在chrome-extension://fpdkndicjblnkakkiiapbbdflkehjmgm/headers.js:132:91
      在miscellaneous_bindings:279:11
      在chrome.Event.dispatchToListener(event_bindings:387:21)
      在chrome.Event.dispatch_(event_bindings:373:27)
      在chrome.Event.dispatch(event_bindings:393:17)
      at Object.chromeHidden.Port.dispatchOnDisconnect(miscellaneous_bindings:238:27)

我尝试运行时遇到此错误。我错过了什么?

2 个答案:

答案 0 :(得分:1)

如何捕获tabId的{​​{1}},如果您正在寻找将消息从chrome.tabs.sendMessage(tabId,传递到{{1}的示例代码,您是否可以发布完整脚本来调试问题?检查一下。

参考

的manifest.json

已注册的Chrome Extension页面和Debugging Tab

popup

popup.html

确保HTML遵守CSP

content scripts

popup.js

将消息传递给内容脚本。

{
 "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
}

selection.js

添加了一个处理程序来捕获从弹出页面发送的消息

<!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>

编辑:

我删除了一些已弃用的API(),例如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; });

,我的代码正常运行

<强> background.js

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

});

<强> content.js

sendResponse

<强> spy.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;
    });
}

如何确保在测试期间不要手动触发开发人员工具。

答案 1 :(得分:1)

好的,我已经弄清楚了。 由于我需要加载页面的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

REMOVED

<强> spy.js

添加了以下

chrome.extension.onMessage.addListener(function(request, sender) {
  console.log("Request.data: " + request.data);
});