最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - Can JavaScript access source code of a <script src=""> element? - Stack Overflow

programmeradmin3浏览0评论
<script id="s1" src="foo.js"></script>
<script>
    alert('foo.js contains' + _source_code_of('s1'))
</script>

Can _source_code_of be implemented?

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

Can _source_code_of be implemented?

Share Improve this question edited Feb 1, 2011 at 13:23 Arnaud Le Blanc 99.9k24 gold badges211 silver badges196 bronze badges asked Feb 1, 2011 at 13:10 SixteaseSixtease 7908 silver badges18 bronze badges 1
  • As far as I know actually Yes it is kind of possible but you have to modify foo.js in a convenient way to allow the other script to be able to get (almost) all its content.. And also you don't even need foo extension to be .js. In fact can be something else too and it still works. All this means that you have to be able to access and edit foo.js the right way. – willy wonka Commented May 29, 2023 at 3:08
Add a ment  | 

2 Answers 2

Reset to default 11

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)

  1. 暂无评论