0

I'm trying to retrieve a script tag from a page using chrome extension. If i open view page source i can see the script tag but if i view it using devtools its not there. The client side removes that script. I have tried this answer the response is same as manipulated by the browser. How can i access the script tag before its removed?

Kamran Arshad
  • 81
  • 1
  • 16
  • 1
    Chrome extensions can't do that but it's possible to read the scripts even **after** they were deleted, see the answer below. In Firefox there is onbeforescriptexecute event. – wOxxOm Mar 20 '20 at 15:24

1 Answers1

0

Use chrome.debugger API to read all running scripts even if their tags are removed.

manifest.json:

"permissions": ["debugger", "activeTab"]

browser_action's popup.js or background.js:

chrome.tabs.query({active: true, currentWindow: true}, async ([tab]) => {
  const pageScripts = await getTabScripts(tab.id);
  console.log(pageScripts);
});
function getTabScripts(tabId) {
  const results = [];
  let resolveMain;
  let timer;
  function onEvent(src, method, info) {
    if (method === 'Debugger.scriptParsed' && info.executionContextId === 1) {
      results.push(getSource(info));
    }
    clearTimeout(timer);
    timer = setTimeout(doResolve, 100);
  }
  function getSource(info) {
    const {scriptId, url} = info;
    return new Promise(resolve =>
      chrome.debugger.sendCommand({tabId}, 'Debugger.getScriptSource', {scriptId},
        e => resolve({code: e.scriptSource, url, info})));
  }
  function doResolve() {
    chrome.debugger.onEvent.removeListener(onEvent);
    chrome.debugger.detach({tabId});
    resolveMain(Promise.all(results));
  }
  return new Promise(resolve => {
    resolveMain = resolve;
    chrome.debugger.attach({tabId}, '1.3', () => {
      chrome.debugger.onEvent.addListener(onEvent);
      chrome.debugger.sendCommand({tabId}, 'Debugger.enable');
    });
  });
}

Unfortunately, it'll temporarily show a panel above the tab about it being debugged but you can reduce the timeout 100 to something like 20 if all results are still getting reported.

wOxxOm
  • 65,848
  • 11
  • 132
  • 136