JavaScript LogoEveryone knows you can view the source code of any web page. But you can also use JavaScript to grab the source code of a different page, and show it in yours

If for some odd reason, you wanted to view the source code of another page without having to actually browse to that page and click “page view source,” you can use JavaScript to do so. In the example below, I use the “window.prompt()” function, to prompt the user for a web page whose source code they would like to see. That function returns the value of the input. We then use the “window.location” method to open up that URL in the browser, but we pre-pend the URL with ‘view-source:’, which achieves the same result as manually browsing to that page, and clicking:  “page view source”.

(Note: As of this writing, this only works in Chrome and FireFox)

As  you can see, the second argument to the window.prompt() method is the default text that we want to appear in the text box. But what if the user accidentally deletes “http://” or simply ignores it, entering something like “”? No problem. We first use the JavaScript  “substring()” method to check to see if the first seven characters of the return value are:  “http://”. If so, great; we just use the return value as is. If it is not, we pre-pend that value with “http://”, and we are all set.

Example # 1:










There may not be too many scenarios in which you need to do this, but it is handy to know now. You never know if, down the road, you might need some kind of variation on this functionality.

Helpful Links