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?
Asked
Active
Viewed 97 times
0

Kamran Arshad
- 81
- 1
- 16
-
1Chrome 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 Answers
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
-
Thanks but the scripts i got using your answer are either `copyright` or anonymous function with 2 or 3 line arbitrary code where url is either empty or `chrome-error://chromewebdata/`. – Kamran Arshad Mar 23 '20 at 08:42
-
-
-
One last thing: try removing `&& info.executionContextId === 1` to see all scripts. – wOxxOm Mar 23 '20 at 08:46
-
I got the page's script but it was without the code which is being removed. Anyways thank you for your help. – Kamran Arshad Mar 23 '20 at 08:58