4

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.

TBG
  • 305
  • 4
  • 10
  • The problem isn't with opening the url. It is just "view-source" was never meant for javascript to use. It is counted as a local resource. – DarthCadeus Apr 18 '19 at 23:44

1 Answers1

4

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).

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • Would it be possible to look for a specific term or string of text in the console after the data is logged to it? – TBG Apr 18 '19 at 23:55
  • Sure, it's probably possible, though the actual code would depend on the what exactly the requirements are, of course – CertainPerformance Apr 19 '19 at 00:22
  • Say the data that was just logged contains the word "correct". I would like the script to look for that word and then grab the whole line of text to be displayed in an alert for the user. Ex: The answer is correct! The script would look for the word "correct" and then use alert() to display the whole line "The answer is correct!" – TBG Apr 19 '19 at 00:58
  • Split the response by lines, then use `.find` to find a line that includes the word you're looking for: `lines.find(line => line.includes('correct'))` – CertainPerformance Apr 19 '19 at 00:59
  • Your answer ended up being way better than opening a `view-source:` window, lol, thx – brasofilo Aug 05 '22 at 15:50