javascript: pass a variable from one page to another

Hey folks,

Is it possible to pass a javascript variable from one page to another? For example, on page1.htm I want to take the pathname (window.location.pathname) put it into a variable, and pass it to a hidden field contained on a form on page2.htm -- or would that be considered xss?

Thanks!
jmoriartyAsked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
exalkoniumConnect With a Mentor Commented:
Let's try again (page2):
function get_array() {
  var vars = [], hash;
  var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
  for(var i = 0; i < hashes.length; i++) {
    hash = hashes[i].split('=');
    vars.push(hash[0]);
    vars[hash[0]] = decoddeURIComponent(hash[1]);
  }
  return vars;
}
vars = get_array();
//vars["pathname"];

Open in new window

0
 
exalkoniumCommented:
You could do this through GET when you ask for page 2:
var pathname = encodeURIComponent(window.location.pathname);

window.location = "page2.htm?pathname=" + pathname; //or however you get to your next page

Open in new window

0
 
exalkoniumCommented:
You could then access them on your next page inside an associative array:
0
The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

 
hieloCommented:
<script>
window.onload=function(){
document.getElementById('hiddenField').value=location.pathname;
}
</script>
<form>
<input type="hidden" name="url" id="hiddenField" value="" />
</form>
0
 
exalkoniumCommented:
And it wouldn't be considered XSS as long as both pages exist on the same domain.
0
 
exalkoniumCommented:
Comment #2 didn't post the code:
function get_array() {
  var vars = [], hash;
  var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
  for(var i = 0; i < hashes.length; i++) {
    hash = hashes[i].split('=');
    vars.push(hash[0]);
    vars[hash[0]] = hash[1];
  }
  return vars;
}

Open in new window

0
 
exalkoniumCommented:
It's not my day. To add to my solution, to use vars:
vars = get_array();
alert(vars["pathname"]);//sample usage

Open in new window

0
 
jmoriartyAuthor Commented:
Hi exalkonium,

That's a great solution you've presented, and should work well, though I think we'll also need to access that vars["pathname"] with decodeURIComponent() to strip the encoding if I'm not mistaken. Going to test it out now.

Thanks to you and others!
0
 
exalkoniumCommented:
Ah, you are correct. Sorry, like I said, not my day...seem to be forgetting a lot.
0
 
jmoriartyAuthor Commented:
That did the trick. Thanks. :)
0
All Courses

From novice to tech pro — start learning today.