google-chrome-extension - 如何将 DOM 从调试选项卡获取到扩展脚本

标签 google-chrome-extension

我在这里寻求一些帮助,因为我看到的示例只是从选项卡到扩展程序,而不是相反。

我正在寻找使用自定义 Chrome 扩展程序调试的页面/选项卡的源代码。我希望扩展程序能够调用一条消息,并将响应发送回进行调用的扩展程序面板 javascript。

list

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

背景.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);});
  }

结果

端口错误:无法建立连接。接收端不存在。杂项绑定(bind):235 chromeHidden.Port.dispatchOnDisconnect 杂项绑定(bind):235

Error in event handler for 'undefined': Cannot read property 'data' of undefined TypeError: Cannot read property 'data' of undefined
at chrome-extension://fpdkndicjblnkakkiiapbbdflkehjmgm/headers.js:132:91
at miscellaneous_bindings:279:11
at 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)

当我尝试运行它时出现此错误。我错过了什么?

最佳答案

您如何捕获chrome.tabs.sendMessage(tabId,)的tabId,如果您正在寻找示例代码,您可以发布完整的脚本来调试问题吗如需将消息从 Chrome 扩展 传递到 调试选项卡,请选中此选项。

引用文献

manifest.json

注册弹出页面和内容脚本

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

选择.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)后,我使您的代码正常工作

背景.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);
});

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

关于google-chrome-extension - 如何将 DOM 从调试选项卡获取到扩展脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14205155/

相关文章:

google-chrome - 拒绝在我的 Chrome 扩展程序中加载很棒的字体资源

javascript - "Attempting to use a disconnected port object"在 chrome 扩展中具有长生命周期连接

javascript - 如何获取正在运行 content.js 的选项卡的选项卡 ID?

javascript - Chrome 扩展跨域 AJAX 给出 NETWORK_ERR : XMLHttpRequest Exception 101

javascript - Vue CLI 3 防止某些输出文件的缓存破坏

javascript - 如何使用 Chrome 扩展程序的 ContentScript 更改 flashvar?

google-chrome - Chrome扩展弹出窗口中的表单发布没有做任何事情

javascript - React 开发工具无法工作 : "Error in event handling for (unknown)"

javascript - 删除特定域的本地存储

javascript - 新标签页上动态 URL 的 Chrome 扩展程序安全策略