Original address: github.com/HuJiaoHJ/bl…

In our usual development work, Chrome developer tools are our indispensable tools, in addition to chrome native tools, there are such as:

  • Use vue-devTools used for VUE development
  • React – devTools used for react development

This article focuses on how these developer tools communicate messages with the page.

First, let’s take an example:

This developer tool source: github.com/HuJiaoHJ/ec… , this tool is a Chrome debugging tool that supports Canvas library (EasyCanvas). It can modify the style and physical properties of canvas elements to achieve wySIWYG effect and improve debugging efficiency. Interested partners can understand by themselves ~

In this article, you will learn how to communicate with Chrome DevTools by using chrome DevTools. You can also learn about the basic components of Chrome DevTools in this article, learn about its basic communication methods, for daily work can also have some reference and help

Chrome DevTools introduction

Chrome DevTools is divided into three parts:

  • DevTools Page: The developer’s tool, which is the panel we use when we use it
  • Background Page is a javascript script in the Background
  • Content Script: A javascript file that is allowed in the context of a web page

The sections are described in detail below, and here is a panoramic view of communication between the three sections:

Let’s take a look at the implementation of each part in detail

  • Web pages communicate with content scripts
  • Content scripts communicate with background pages
  • The background page communicates with the developer tools
  • How do web messages get passed to developer tools?
  • How do developer tool messages get to the page?

Web pages communicate with content scripts

A Content Script is a JS file that runs in the context of a web page and can be used to retrieve the DOM and capture DOM events.

Web pages cannot communicate directly with the DevTools Page. Instead, they need to listen for web events in content scripts and pass messages to background pages via the Chrome.Runtime API.

Content scripts can listen for web page DOM events or window.postMessage events as follows:

web page

window.postMessage({
    name: 'hello wolrd'
}, The '*');
Copy the code

content-script.js

window.addEventListener('message', e => {
    if (e.source === window) { chrome.runtime.sendMessage(e.data); }});Copy the code

Content scripts communicate with background pages

Background pages, although called pages, are actually js scripts in the background.

Content script to monitor event triggers, by chrome. Runtime. The sendMessage () method will messaging to Background Page, Background Page).

The background script by chrome. Runtime. OnMessage. AddListener () method to monitor the message, as follows:

background.js

chrome.runtime.onMessage.addListener((message, sender, sendResponse) = > {
    if (sender.tab) {
        consttabId = sender.tab.id; . }else {
        console.log("sender.tab not defined.");
    }
    return true;
});
Copy the code

The background page communicates with the developer tools

Background pages communicate with developer tools through a long connection. (Chrome. Runtime API) :

devtool.js

// Communicate with background page messages - long connection
const port = chrome.runtime.connect({name: 'devtools'});
// Listen for background page messages
port.onMessage.addListener((message) = >{... });// Send messages to background pages
port.postMessage({
    name: 'original'.tabId: chrome.devtools.inspectedWindow.tabId
});
Copy the code

background.js

chrome.runtime.onConnect.addListener(function (port) {
 
    const extensionListener = function (message, sender, sendResponse) {
        if (message.name == 'original') {... }}; port.onMessage.addListener(extensionListener); port.onDisconnect.addListener(function(port) {
        port.onMessage.removeListener(extensionListener);
    });
});
Copy the code

Above, it introduces the communication between web page and content script, content script and background page, background page and developer tools, so it can be found that the message of the web page is through content script, background page, and finally reach the developer tools, so how to reach the message of the content script to the development tools?

How do web messages get passed to developer tools?

The obvious thing is to use the background page as a bridge to pass messages from the content script to the developer tools. The specific code is as follows:

background.js

// Act as a bridge between content Script and devtool
const connections = {};
 
chrome.runtime.onConnect.addListener(function (port) {
 
    const extensionListener = function (message, sender, sendResponse) {
        if (message.name == 'original') { connections[message.tabId] = port; }}; port.onMessage.addListener(extensionListener); port.onDisconnect.addListener(function(port) {
        port.onMessage.removeListener(extensionListener);
 
        const tabs = Object.keys(connections);
        for (let i = 0, len = tabs.length; i < len; i++) {
            if (connections[tabs[i]] == port) {
                delete connections[tabs[i]];
                break; }}}); });// Receive messages from content scripts and send them to devtool
chrome.runtime.onMessage.addListener((message, sender, sendResponse) = > {
    if (sender.tab) {
        const tabId = sender.tab.id;
        if (tabId in connections) {
            connections[tabId].postMessage(message);
        } else {
            console.log("Tab not found in connection list."); }}else {
        console.log("sender.tab not defined.");
    }
    return true;
});
Copy the code

This completes the process of sending a message from the web page to the developer tool. How does the developer tool send a message to the web page?

How do developer tool messages get to the page?

There are two main ways in which messages from developer tools can be delivered to a web page:

1, the direct use of chrome. Devtools. InspectedWindow. Eval () method, in the context of web js code execution, as follows:

devtool.js

chrome.devtools.inspectedWindow.eval('console.log(window)');
Copy the code

2, The developer tool passes the message to the background page via a long connection. In the background page, the javascript code is executed by calling chrome.tab.excutescript (), as follows:

background.js

chrome.tab.excuteScript(tabId, {
    code: 'console.log(window)'
});
Copy the code

The first method ~ is recommended

Above, introduces the whole process of communication between the web page and developer tools ~~~

The above means of communication have been used in the tools mentioned at the beginning of the article, the warehouse: github.com/HuJiaoHJ/ec… In fact, it basically covers all the communication methods of chrome developer tools

Write in the last

After learning the chrome DevTools communication mode, you can have fun developing your own developer tools, hope to have a need for partners

If you like my articles, go to my personal blog star ⭐️