简体   繁体   English

在自定义Chrome开发者工具面板和Chrome扩展程序内容脚本之间直接通信

[英]Communicate directly between custom Chrome devtools panel and Chrome Extension content script

My question is: is there a way to communicate directly between my custom Chrome DevTools panel and my Chrome Extension's content script? 我的问题是:是否可以在自定义Chrome DevTools面板和Chrome Extension的内容脚本之间直接通信? Right now, it seems like I need to use the background script as a mediator between the content script and the devtools panel. 现在,似乎我需要使用后台脚本作为内容脚本和devtools面板之间的中介。

I tried using a custom window event: 我尝试使用自定义窗口事件:

// in the dev tools panel //在开发工具面板中

let event = new Event('suman-dev-tools', {
  value: 'foo'
} as any);


window.dispatchEvent(event);

// in the content script //在内容脚本中

window.addEventListener('suman-dev-tools', function(ev){
  console.log('my devtools panel has spoken:', ev);
});

but that doesn't seem to work - it looks like I can't use window events to communicate between the two things. 但这似乎不起作用-看来我无法使用窗口事件在两件事之间进行通信。 Must I use the background page to communicate between devtools page and content script? 我必须使用后台页面在devtools页面和内容脚本之间进行通信吗?

As you mentioned the best practice is to use background script as a message broker. 正如您提到的,最佳实践是将后台脚本用作消息代理。

But there is one more way to run code in content-script directly from devtool panel: devtools.inspectedWindow.eval with useContentScriptContext: true allows you to evaluate code in the content-script scope. 但是,还有另一种直接从devtool面板运行内容脚本中代码的方法:带useContentScriptContext: true devtools.inspectedWindow.eval useContentScriptContext: true允许您评估内容脚本范围内的代码。

chrome.devtools.inspectedWindow.eval('<your code>', {
    useContentScriptContext: true
}, function(result) {
    // result of the execution
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Chrome DevTools 和扩展中的内容脚本之间的通信 - Communicating between Chrome DevTools and content script in extension Chrome扩展程序:在内容脚本和网页脚本之间进行通讯 - Chrome extension:Communicate between content script and webpage's script 在使用 manifest v3 的浏览器扩展中,如何在内容脚本和开发工具面板之间进行通信? - In a browser extension using manifest v3, how can I communicate between a content script and a devtools panel? Chrome DevTools扩展:如何从内容脚本中的元素面板中获取所选元素? - Chrome DevTools extension: how to get selected element from elements panel in content script? 与Chrome扩展程序中内容脚本中的页面脚本进行通信 - Communicate with a page script from a content script in a Chrome extension 内容脚本不与后台脚本通信 - chrome 扩展 - Content script doesn't communicate with background script - chrome extension Chrome扩展程序,如何从面板向内容脚本发送消息 - Chrome extension, how to send message from panel to content script 如何在内容脚本和面板之间进行通信 - How to communicate between content script and the panel Chrome扩展程序:devtools面板可以接收一次性消息吗? - Chrome extension: can devtools panel receive one-time messages? Chrome devtools为IndexedDB扩展 - Chrome devtools extension for IndexedDB
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM