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

邮差的信 提交于 2019-12-04 13:04:15

问题


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 the menu, the corresponding element on the webpage is highlighted.

I saw Chrome devtools highlights an element when you right click and inspect on it. I'm curious if there is some highlighting API accessible from DevTools? If not, how does one highlight elements similar to how devtools does it?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/45985234/how-to-highlight-elements-in-a-chrome-extension-similar-to-how-devtools-does-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!