Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use window.open to open a URL stored in a variable

Tags:

javascript

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.

like image 299
TBG Avatar asked Sep 08 '25 14:09

TBG


1 Answers

Opening windows (or having <a hrefs) 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).

like image 135
CertainPerformance Avatar answered Sep 10 '25 04:09

CertainPerformance