How to highlight elements in a Chrome Extension similar to how DevTools does it?

前端 未结 2 1643
闹比i
闹比i 2021-02-09 18:18

I\'m interested in creating a Chrome Extension which lists all the elements on the webpage that have an \'id\' attribute in a menu. Then, when the user clicks on the element in

相关标签:
2条回答
  • 2021-02-09 18:48

    You can use the exact API that Chrome DevTools are using. You will need to call highlightQuad or highlightNode via debugger API. You can even specify the color and you can be certain that the highlight will render correctly and not interfere with the website (injecting an 'overlay' node, as Xan suggested, doesn't guarantee that). On the other hand, it will be much trickier to get right and user won't be able to use both your extension and DevTools at the same time (there can be only one debugger API connection). This code should get you started.

    0 讨论(0)
  • 2021-02-09 18:54

    Chrome API does not provide access to such highlighting; you'll need to implement it yourself with an overlay.

    Chrome API does provide access to the same functionality as DevTools if you use the debugger API. See this answer for details.

    Before Chrome 63 (2017-12-06), writing a DevTools extension (i.e. using devtools.* APIs to display UI in DevTools) and using debugger at the same time would've been impossible, as only one instance of a debugger protocol client was allowed at once. This has changed, so now it's a viable answer, even if the documentation for chrome.debugger API wasn't updated yet.

    Even though it's now possible, be aware that debugger API is an API with heavy warnings (adding it after publication may auto-disable installed extensions - needs testing).

    Below is the original answer:


    You can implement the highlighting yourself with an overlay.

    You can study how it's usually done by looking, for example, at the element picker of uBlock Origin.

    In short, that method creates an SVG overlay using, among other things, getBoundingClientRect() of the elements selected.

    0 讨论(0)
提交回复
热议问题