And*_*ley 6 html javascript xss load external
是否可以检测可能通过浏览器加载项,代理,xss等加载到页面中的外部脚本?
说我有这个网页:
<html>
<head>
<title>Hello world!</title>
<script src="http://mydomain.com/script.js"></script>
</head>
<body>
Hello world!
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
是否可以在我的script.js文件中包含一些脚本,以检测页面上的其他脚本元素何时不来源http://mydomain.com?
我想要的东西可以检测源中包含的其他脚本(即onload事件触发时它们存在)和页面加载后的任何时间添加的脚本.
如果我能检测到这些脚本,我还能以某种方式阻止它们吗?
如果我知道还有其他的事情发生,这对于调试用户报告的javascript/ui问题很有用.
我使用jQuery,所以jQuery的答案对我有用.我只是不想限制jQuery的答案.
编辑
我的解决方案如下.但是,它有两个(潜在的)问题:
url()值的规则)加载的外部资源.如果有人想提交一个解决其中一个或两个问题的答案,我会赞成.
如果你两个都解决了,我会接受你的回答.
我对收到的答案并不满意(尽管我很欣赏Andreas K\xc3\xb6berle\ 的建议),所以我决定自己解决这个问题。
\n\n我编写了一个函数,可以按需运行并识别任何具有外部来源的 html 元素。这样,我可以在报告 javascript 错误时运行它,以获取有关环境的更多信息。
\n\n取决于 jQuery(抱歉,元素选择非常容易)和parseUri()(复制在这个答案的底部)
/**\n * Identifies elements with `src` or `href` attributes with a URI pointing to\n * a hostname other than the given hostname. Defaults to the current hostname.\n * Excludes <a> links.\n * \n * @param string myHostname The hostname of allowed resources.\n * @return array An array of `ELEMENT: src` strings for external resources.\n */\nfunction getExternalSources(myHostname)\n{\n var s, r = new Array();\n if(typeof myHostname == \'undefined\')\n {\n myHostname = location.hostname;\n }\n $(\'[src], [href]:not(a)\').each(function(){\n s = (typeof this.src == \'undefined\' ? this.href : this.src);\n if(parseUri(s).hostname.search(myHostname) == -1)\n {\n r.push(this.tagName.toUpperCase() + \': \' + s);\n }\n });\n return r;\n}\nRun Code Online (Sandbox Code Playgroud)\n\nvar s = getExternalSources(\'mydomain.com\');\nfor(var i = 0; i < s.length; i++)\n{\n console.log(s[i]);\n}\n\n// Can also do the following, defaults to hostname of the window:\nvar s = getExternalSources();\nRun Code Online (Sandbox Code Playgroud)\n\n搜索包含子域,因此在上面的示例中将允许源为www.mydomain.com或 的元素。img.mydomain.com
请注意,这不会获取 CSS@import规则中的外部来源(或任何具有与url()此相关的 CSS 规则)。如果有人愿意贡献可以做到这一点的代码,我将投票并接受您的答案。
parseUri()下面是我从https://gist.github.com/1847816获得的代码(并稍加修改)。
(function(w, d){\n var a,\n k = \'protocol hostname host pathname port search hash href\'.split(\' \');\n w.parseUri = function(url){\n a || (a = d.createElement(\'a\'));\n a.href = url;\n for (var r = {}, i = 0; i<8; i++)\n {\n r[k[i]] = a[k[i]];\n }\n r.toString = function(){return a.href;};\n r.requestUri = r.pathname + r.search;\n return r;\n };\n})(window, document);\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
4918 次 |
| 最近记录: |