简体   繁体   中英

How to have a JS function open a new HTML page and then run?

In a multiple-page app I'm building (coding student project), I have a requirement where a click on one HTML page is supposed to:

  • take an input from that click, open a different HTML page,
  • use the click input information (from the previous page) as a function argument,
  • run that function and display the results on the now-current page.

I tried to use onclick on the "first" page to run the function, and then put the

 window.open("new_page")

into the function itself, but that doesn't work - the window.open method does open the new page, but it seems to "delete" all function results, regardless if I put window.open at the very top or bottom of the function definition.

What is the proper way to do this in JS?

If your website implementation is exclusively client-side (without any server-side scripting eg PHP), here are two possible ways to do it:

1- Use localStorage:

Basically, localStorage allows your web application to store properties (as key-value pairs) in your browser, which you can access throughout your website. More information .

//in the first page, you can set a property
localStorage.setItem("key", value);

//then from the second page you can access it like so:
var val = localStorage.getItem("key");

2- Add query string parameters to the URL you are redirecting to:

You can add GET request parameters to your redirect by simply appending a query string to your URL, so to pass a parameter called "key" with value of "value", you can do:

window.open("new_page?key=value") //the URL will now look like this

And then from the second page, you can retrieve the value like so:

var urlParams = new URLSearchParams(window.location.search);
var val = urlParams.get('key');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM