Is there an equivalent of the onbeforescriptexecute or beforescript execute event in Chrome? I would like to intercept and print out the javascript code that is being executed before any javascript on the page is loaded. This should include Javascript within script tags and other attributes like onblur, etc.
Thanks
Is there an equivalent of the onbeforescriptexecute or beforescript execute event in Chrome? I would like to intercept and print out the javascript code that is being executed before any javascript on the page is loaded. This should include Javascript within script tags and other attributes like onblur, etc.
Thanks
- You could maybe achieve it with defer and or async see this peter.sh/experiments/… article which explain their use and why we have them – Simon Dragsbæk Commented Aug 8, 2013 at 8:26
3 Answers
Reset to default 7Here is a polyfill of onbeforescriptexecute
event: https://gist.github./jspenguin2017/cd568a50128c71e515738413cd09a890
It works on Chrome and Edge, but ironically not on Firefox.
To print the script content, just do console.log(e.script.textContent);
inside the event handler. You can call e.replacePayload(payload);
to change the script to run, or e.preventDefault()
to block the script.
e.preventDefault();
takes precedence over e.replacePayload(...);
, if e.replacePayload(...);
is called multiple times, the last call will override all previous calls. You can call e.stopPropagation();
to ensure your new payload gets registered.
Unfortunately, textContent
does not always work properly for huge scripts. It should be fine for debugging. Also, it only works for "hard coded" inline scripts, not those dynamically injected from other scripts. You can still monitor those scripts, but you can't interfere with their execution.
It's a bit tricky for onblur
, you might have to use a custom observer that scans for it.
I think it's only for Firefox :( Sorry.
A really bad advice:
Well, by default scripts are loaded in a sync (with space, as opposed to async
) way.
So, you can access the latest loaded script tag looking for last existing <script>
tag in head (which is almost exactly the opposite thing of what you're trying to achieve.
I'll be glad to see any other answer (probably a much better one) to your question, but it the whole idea of using that kind of behaviour looks bad to me.
A slightly better one
Usually, to do something like that you should load scripts via ajax and handle them before they're added to DOM and executed.
The best solution in my opinion would be using asynchronous modules with AMD loaders such as require.js this should keep your code more organized.
I do realize it doesn't solve your problem, but hopefully I helped yo a little bit :)
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742336604a4424775.html
评论列表(0条)