Link to home
Start Free TrialLog in
Avatar of jmoriarty
jmoriarty

asked on

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!
Avatar of exalkonium
exalkonium
Flag of United States of America image

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

You could then access them on your next page inside an associative array:
Avatar of hielo
<script>
window.onload=function(){
document.getElementById('hiddenField').value=location.pathname;
}
</script>
<form>
<input type="hidden" name="url" id="hiddenField" value="" />
</form>
And it wouldn't be considered XSS as long as both pages exist on the same domain.
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

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

Avatar of jmoriarty
jmoriarty

ASKER

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!
Ah, you are correct. Sorry, like I said, not my day...seem to be forgetting a lot.
ASKER CERTIFIED SOLUTION
Avatar of exalkonium
exalkonium
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
That did the trick. Thanks. :)