0

There have been many questions and answers to whether and how it is possible to get the source code of a webpage for usage in a chrome extension.

I would like to get hold of the JavaScript source code however, not the DOM tree.

I need to get the content of each used JavaScript file.

Through the DOM tree I can access which JavaScript files are referenced, but how could I get the content of those for usage in my chrome extension?

bergben
  • 1,385
  • 1
  • 16
  • 35
  • 1
    The only way to get the current JavaScript snapshot of the page is to use `chrome.debugger` API to attach to the tab and then emit [Debugger.enable](https://chromedevtools.github.io/devtools-protocol/tot/Debugger#method-enable) and register a listener for `Debugger.scriptParsed` event to collect the info, then get the actual text of the scripts via `Debugger.getScriptSource` method. This is how devtools itself enumerates the page scripts so you can use [devtools "protocol monitor" panel](https://puu.sh/E0LS5/ec801f98fd.png) to see how it uses the API. Use google search for more info. – wOxxOm Aug 03 '19 at 14:24
  • Thanks for the tip! Would I do all this in the content script and then message it to the popup? I need it in the popup.js – bergben Aug 03 '19 at 15:52
  • 1
    You should do it in your popup script or a background script. Look for examples and demo extensions for more info. – wOxxOm Aug 03 '19 at 15:54
  • If I'm not mistaken I need to do it in the background script, because the popup might not be open on page load. The debugger however only gets enabled when opening the popup if it's implemented there, missing all the `Debugger.scriptParsed` events of the initial files. So I'll need to listen to current tab in background script, do the steps you described, and message them back to the popup.js once executed – bergben Aug 03 '19 at 17:54
  • But since the debugger can only be attached to one tab I run into the problem that when the user switches tabs while pages are loading then I will never get the complete source, only that part that was loaded while the user was in the current tab – bergben Aug 03 '19 at 17:59
  • So all the already parsed scripts will be fired an event for too? – bergben Aug 03 '19 at 18:01
  • 1
    Particularly to [Debugger.scriptParsed](https://chromedevtools.github.io/devtools-protocol/tot/Debugger#event-scriptParsed) description: "This event is also fired for all known and uncollected scripts upon enabling debugger." – wOxxOm Aug 03 '19 at 18:34

0 Answers0