Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>

Can _source_code_of be implemented?

like image 658
Sixtease Avatar asked Feb 01 '11 13:02

Sixtease


People also ask

How does src work JavaScript?

The src attribute specifies the URL of an external script file. If you want to run the same JavaScript on several pages in a web site, you should create an external JavaScript file, instead of writing the same script over and over again.

Where can I see JavaScript source code?

For most browsers, to view inline JavaScript in the HTML source code, do one of the following. Press the Ctrl + U keyboard shortcut. Right-click an empty area on the web page and select the View page source or similar option in the pop-up menu.

Can we write JavaScript code in script tag?

Reference the External Script File A <script> tag can also be used to include an external script file to an HTML web page by using the src attribute. If you don't want to write inline JavaScript code in the <script></script> tag, then you can also write JavaScript code in a separate file with .


2 Answers

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);
});
like image 91
Arnaud Le Blanc Avatar answered Oct 05 '22 03:10

Arnaud Le Blanc


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.

like image 30
leebriggs Avatar answered Oct 05 '22 05:10

leebriggs