Is it possible to detect external scripts that might be loaded into a page by browser add-ons, a proxy, xss, etc?
Say I have this web page:
<html>
<head>
<title>Hello world!</title>
<script src="http://mydomain.com/script.js"></script>
</head>
<body>
Hello world!
</body>
</html>
Would it be possible to include some script in my script.js file that would detect when other script elements on the page do not originate from http://mydomain.com?
I want something that could detect other scripts somehow included in the source (i.e. they are present when the onload event fires) and scripts added any time after page load.
If I can detect those scripts, can I also stop them somehow?
This would be useful in debugging javascript/ui issues reported by users if I knew there was other stuff going on.
I use jQuery, so a jQuery answer will work for me. I just didn’t want to limit answers to jQuery only.
EDIT
My solution is below. However, there are two (potential) problems with it:
- It depends on jQuery.
- It will not detect foreign resources loaded via CSS @import rules (or any rule with a
url()value).
If someone would like to submit an answer that solves one or both of those issues, I will upvote it.
If you solve both, I will accept your answer.
I wasn’t satisfied with the answers I received (though I appreciate Andreas Köberle’s advice), so I decided to tackle this myself.
I wrote a function that could be run on demand and identify any html elements with foreign sources. This way, I can run this whenever reporting a javascript error to get more information about the environment.
Code
Depends on jQuery (sorry, element selection was just so much easier) and
parseUri()(copied at the bottom of this answer)Usage
The search is inclusive of subdomains, so elements with sources of
www.mydomain.comorimg.mydomain.comwould be allowed in the above example.Note that this will not pick up on foreign sources in CSS
@importrules (or any CSS rule with aurl()for that matter). If anyone would like to contribute code that can do that, I will upvote and accept your answer.Below is the code for
parseUri(), which I obtained from https://gist.github.com/1847816 (and slightly modified).