2

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

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

显现

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

内容.js

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

间谍.html

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

间谍.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

“未定义”的事件处理程序错误:无法读取未定义的属性“数据”类型错误:无法
在 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)
在 Object.chromeHidden.Port.dispatchOnDisconnect (miscellaneous_bindings:238 :27)

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

4

2 回答 2

1

好的,我已经想通了。由于我需要加载页面的 DOM,我将在我的后台页面中使用 chrome.tabs.onUpdated.addListener 在页面加载时发送代码。这样我就不必依赖选项卡和扩展程序之间的 2 路通信。

显现

删除 content.js

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

内容.js

已移除

间谍.js

添加了以下内容

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

你是如何捕获tabIdchrome.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;
});

选择.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;
    });
}

内容.js

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

间谍.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 回答