开发者

Can JavaScript access source code of a <script src=""> element?

<script id="s1" src="foo.js"></script>
<script>
    alert('foo.js contains' + _source_code_of('s1'))
</script>

C开发者_运维技巧an _source_code_of be implemented?


No, this would allow to retrieve the contents of any URL, which would break some security policies. (This would be an equivalent of an ajax get request without same-domain checks.)

However, since foo.js is on the same domain than the page you can fetch it with an ajax request. Example with jQuery:

$.get('foo.js', function(source_code) {
    alert('foo.js contains ' + source_code);
});


No, not directly for fundamental security reasons.

The fact that you've tagged this with Ajax implies that you're trying to use this as a way to retrieve data. If so, the closest similar approach is JSONP, in which the newly loaded script invokes a method to pass data back to the parent document.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜