MCPcopy Create free account
hub / github.com/Wscats/chrome-devtools-cli / Tool

Class Tool

src/core/panel.ts:1–70  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

1class Tool {
2 public port: any;
3 public listen: any;
4 public send: any;
5 constructor() {
6 // 初始化,与 background.ts 建立连接
7 let { port, listen, send } = this.sendMessageToBackground();
8 this.port = port;
9 this.listen = listen;
10 this.send = send;
11 }
12 // 1.panel.ts 与 inject.ts 的通信方案,使用链接的方式
13 injectScriptLinkToPage = (scriptName: string, cb: Function): void => {
14 const src = `
15 (function() {
16 var script = document.constructor.prototype.createElement.call(document, 'script');
17 script.src = "${chrome.runtime.getURL(scriptName)}";
18 document.documentElement.appendChild(script);
19 // script.parentNode.removeChild(script);
20 })()
21 `;
22 chrome.devtools.inspectedWindow.eval(src, (res, err) => {
23 if (err) {
24 console.log(err);
25 }
26 cb();
27 });
28 };
29 // 2.panel.ts 与 inject.ts 的通信方案,使用字符串的方式
30 injectScriptStringToPage = (message: string, callback: Function = null) => {
31 chrome.devtools.inspectedWindow.eval(message, (value) => {
32 callback && callback(value);
33 });
34 };
35 // 3.panel.ts 与 content.ts 的通信方案
36 sendMessageToContent = (message: any) => {
37 window.postMessage(message, '*');
38 };
39
40 // 4.panel.ts 与 background.ts 的通信方案,注意是一个长连接
41 // 使用 window.postMessage({name:1}, '*')测试
42 sendMessageToBackground = () => {
43 // 建立长连接
44 const port = chrome.runtime.connect({ name: 'devtools' });
45 // 监听断开
46 // 主动关闭使用 port.disconnect();
47 port.onDisconnect.addListener(() => { });
48 // 监听 background.ts 消息
49 // port.onMessage.addListener((message) => {
50 // console.log(`后台已传来消息:${JSON.stringify(message)}`);
51 // return true;
52 // });
53 // 往 background.ts 发送消息
54 port.postMessage({
55 name: 'original',
56 tabId: chrome.devtools.inspectedWindow.tabId
57 });
58
59 // 释放 port 用于在外部监听
60 return {

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected