First, I am getting the URL of the website currently open and storing that value inside a variable. Then I declare a new variable which adds "view-source:" + the variable with the URL I had previously declared. This prints out the address to the source code of said website.
I want to be able to use window.open so that the new value stored in the second variable is used as the URL inside the parameters. Here is my code:
let page = window.location.href;
let sourcecode = "view-source:" + page;
window.open(sourcecode);
How can I achieve this? Alternatively, is there a way to open the source code directly through JavaScript? Thanks.
Opening windows (or having <a href
s) which start with view-source:
is forbidden in major browsers, unfortunately: it's a security issue.
From a loaded page, there's no generic way to identify the view-source content, unfortunately. However, in many situations, you can fetch the page again, and examine the response text. For example, if the URL you're on is https://jsonplaceholder.typicode.com/, you could do:
fetch('https://jsonplaceholder.typicode.com/')
.then(res => res.text())
.then((responseText) => {
console.log(responseText);
});
If nothing in the HTML changes the DOM before the final end tag, then you can reliably check the innerHTML
in a script tag that runs just before the end of parsing, for example:
console.log(document.documentElement.innerHTML);
But this will not work if any <script>
s change the DOM before DOMContentLoaded (and many do).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With