Chrome DevTools extension: how to get selected element from elements panel in content script?

会有一股神秘感。 提交于 2019-11-30 09:13:21

The API for chrome.devtools.inspectedWindow has been updated to support executing scripts in the context of the content script.

This update in the official Chrome API obsoletes our hacks described above. We can now achieve the expected result with:

chrome.devtools.inspectedWindow.eval("aContentScriptFunction($0)", 
    { useContentScriptContext: true });

The $0 parameter will reference the element selected in the Elements panel.

my way of doing it is sort of a hack too.. instead of injecting a content script defined in your extention you can inject a script tag pointing to your files online (or locally, relative to inspected html ):

//devtools.js
var str = "var s = document.createElement('script');" +
      "s.src = 'http://extentionDomain/extentionFile.js';" +
      "document.body.appendChild(s);";
chrome.devtools.inspectedWindow.eval(str);

online file defines a global:

var myExtention = { doStuff: function(selectedElement){ ..}}

and devtools can call it and pass it the selected element:

chrome.devtools.panels.elements.onSelectionChanged.addListener(function(){
    chrome.devtools.inspectedWindow.eval('myExtention.doStuff($0)');});

however i have not found a way to send a reference back from the inspected window to the devtools extention with this setup.

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