0

Hi,

I am trying to load HTML code and display it on my site based on the URL parameters. I want it to work like this. My shortcut (Siri Shortcuts) will redirect people to https://example.com/index.html?page=[HTML CODE HERE]. Then the HTML code that is in that URL variable, will display on the site (not the blank text but overwrite the existing code so it will display that HTML page). The problem is I am doing it with this code below.

window.onload = function() {
  try {
    var url_string = (window.location.href).toLowerCase();
    var url = new URL(url_string);
    var page = url.searchParams.get("page");
    document.write(page);
  }
}

It works fine when I want it to output 'test' (https://example.com/index.html?page=test). But when I put the whole HTML code in the url variable, it won't output anything.

NOTE: I am still new to HTML and JS.

Peter
  • 9
  • 3
  • The part of the URL after the question mark is called a query string. Try searching for 'html in query strings' for some help. [Example](https://stackoverflow.com/questions/3204879/how-to-pass-html-code-in-query-string). – wazz Aug 27 '21 at 09:05
  • @wazz They ARE using the query string – mplungjan Aug 27 '21 at 09:06
  • Uhh, I know. What? – wazz Aug 27 '21 at 09:07
  • It is bad practice to pass HTML between pages. Pass the data you want to write and then have the recieving page parse the query parameters and render them – mplungjan Aug 27 '21 at 09:07
  • Btw, I also know that. Just leaving it to the OP to figure it out. – wazz Aug 27 '21 at 09:08

1 Answers1

0
  1. document.write wipes the page, script and all. that is Why is document.write considered a "bad practice"?

  2. If you must pass data between pages, pass the data only and update existing code on the new page. So for example have

    <p id="test"></p> 
    

on the page and ?pageContent=somecontent in the URL

Then you can do

var pageContent = url.searchParams.get("pageContent"); 
document.getElementById("test").textContent=pageContent; 

instead of ?page=<p id="test">somecontent</p>

Alternative is to call the server for more content using AJAX, and update the page dynamically with that content.

mplungjan
  • 169,008
  • 28
  • 173
  • 236