4

(我已阅读this,并没有工作,我已经做了很多搜索和实验都无济于事。)在扩展的Chrome DevTools和内容脚本之间的沟通

我写的是Chrome扩展程序(BigConsole),目标是为Chrome开发人员工具构建更好的“控制台”选项卡。这意味着我想在页面的上下文中执行用户输入的代码,以访问页面上的DOM和其他变量。要做到这一点,通信的结构如下:

  • devtools创建panel其中用户编写代码
  • 当用户想要从panel执行代码,所述panel发送一个消息给一个background脚本代码
  • background脚本从panel接收消息/码并将其传递到content脚本将其注入到所述页面
  • content脚本recei VES从background脚本消息/代码和注入一个script元件到其中,然后运行该代码
  • script在页面上的结果然后回发到content脚本window.postMessage
  • content的页面脚本侦听来自该网页的信息/结果并将其传递到background脚本
  • background脚本接收消息/从content脚本导致并将其传递到panel
  • panel接收messag从background脚本E /导致并将其插入到日志结果

呼的。

现在,当用户试图运行代码时,没有任何反应。我在代码中放了一堆console.log(),但控制台中没有任何东西出现。我的主要问题是,我在这里做了什么错误的消息传递,导致什么都没有发生?或者,我很乐意被告知我这样做太复杂,并且有更好的做事方式。下面简化代码...

panel.js:

window.onload = function() { 
     var port = chrome.runtime.connect({name: "Eval in context"}); 
     // Add the eval'd response to the console when the background page sends it back 
     port.onMessage.addListener(function (msg) { 
     addToConsole(msg, false); 
     }); 
     document.getElementById('run').addEventListener('click', function() { 
     var s = document.getElementById('console').value; 
     try { 
      // Ask the background page to ask the content script to inject a script 
      // into the DOM that can finally eval `s` in the right context. 
      port.postMessage(s); 
      // Outputting `s` to the log in the panel works here, 
      // but console.log() does nothing, and I can't observe any 
      // results of port.postMessage 
     } 
     catch(e) {} 
     }); 
    }; 

background.js:

chrome.runtime.onConnect.addListener(function (port) { 
     // Listen for message from the panel and pass it on to the content 
     port.onMessage.addListener(function (message) { 
     // Request a tab for sending needed information 
     chrome.tabs.query({'active': true,'currentWindow': true}, function (tabs) { 
      // Send message to content script 
      if (tab) { 
      chrome.tabs.sendMessage(tabs[0].id, message); 
      } 
     }); 
     }); 
     // Post back to Devtools from content 
     chrome.runtime.onMessage.addListener(function (message, sender) { 
     port.postMessage(message); 
     }); 
    }); 

content.js:

// Listen for the content to eval from the panel via the background page 
    chrome.runtime.onMessage.addListener(function (message, sender) { 
     executeScriptInPageContext(message); 
    }); 
    function executeScriptInPageContext(m) { alert(m); } 

回答

3

正如Alex指出的那样,这是代码中的一个错误,它阻止了它的工作。

放下当前的代码并使用chrome.devtools.inspectedWindow.eval直接运行代码并解析结果。这就简化了复杂的逻辑:

  • devtools创建了用户编写代码
  • devtools面板运行的代码
  • devtools手柄导致

PS。有一种方式来操纵现有的控制台,但我建议不要使用它,除非它是个人使用。在this answer中显示了两种不同的方法。

+0

太棒了,谢谢!奖励点不仅仅是让我更好地正式做到这一点,而且是非正式的更好的方式。 :) – IceCreamYou

相关问题