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.

1
  • 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. Commented Apr 18, 2019 at 23:44

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

5 Comments

Would it be possible to look for a specific term or string of text in the console after the data is logged to it?
Sure, it's probably possible, though the actual code would depend on the what exactly the requirements are, of course
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!"
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'))
Your answer ended up being way better than opening a view-source: window, lol, thx

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.