0

From a webpage www.foo.com, a user clicks a feedback hyperlink to submit feedback about something. It opens a new page with text fields to fill out. What I would like to do is get the URL of the original page www.foo.com for example, to appear in a readonly field on the new page.

This is what I currently have as my test code on my feedback page.

<input id="URL" type="text" name="pageURL" readonly> <script type="text/javascript"> document.getElementById('URL').value = document.location.href; </script>

This displays the URL of the feedback page, page Y, which is what I would expect.

But I'm drawing a blank on how I would get the url of page X, in this example, www.foo.com to appear in the readonly.

I would assume I have to do something in the code for the original page and have that carry over. I do have CORS functioning for other purposes but the information I'm using for that is being brought to a php file instead of the .htm file the form page operates on. I'm still a beginner with CORS but I wouldn't think something like a URL would require it. Or maybe this is mindblowingly simple.

JoeL
  • 710
  • 4
  • 18
  • If you're not bothered about supporting older browsers, you could probably use local storage. Easier than cookies and other libraries, imho [link](http://www.w3.org/TR/2009/WD-webstorage-20091222/) – Equalsk Jun 29 '15 at 19:35
  • Sorry for multiple comments, but the accepted answer on this SO post describes it better than I ever could https://stackoverflow.com/questions/29986657/global-variable-usage-on-page-reload – Equalsk Jun 29 '15 at 19:39

1 Answers1

0

One way to do it is to include the url of the first page in a query variable when linking to the second page.

To do this, you add ?firstpage=FIRSTPAGEURL to the end of the url, where FIRSTPAGEURL is an encoded url of the first page using encodeURIComponent(str) to make it a valid url.

<a href="http://example.com?firstpage=http%3A%2F%2Ffoo.com">Go to second page</a>

Then, on the second page you can get the url of the first page by getting it from the query string:

var url = getQueryVariable('firstpage'); // Get the encoded url
url = decodeURIComponent(url); // Decode the url

function getQueryVariable(variable) {
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i = 0; i < vars.length; i++) {
    var pair = vars[i].split("=");
    if (pair[0] == variable) { return pair[1]; }
  }
  return false;
}

Reference

https://css-tricks.com/snippets/javascript/get-url-variables/

thaliaarchi
  • 152
  • 2
  • 8