2

I have access to the <head> tag on both pages and I need to send data from one page to another. Both pages are on different domains.

Page A domain (www.foo.com)

Page B domain (www.bar.com)

If I declared a variable, say var test_parameter = 'something';... How would I get that variable from one page to the next using some sort of code in the <head> tag?

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
jesse rurka
  • 21
  • 1
  • 2
  • You either need to post to a server script that enables CORS, or you have to put the value in a URL query parameter. – Barmar Feb 26 '21 at 21:26

2 Answers2

3

You can use Window.postMessage as long as one page opened the other.


Page A (https://example.org)

var test_parameter = 'something';

Window.open('https://example.net')
      .postMessage(test_parameter, 'https://example.net');

Page B (https://example.net)

window.addEventListener('message', (event) => {
    
    // Do not do anything unless the message was from
    // a domain we trust.
    if (event.origin !== 'https://example.org') return;

    // Create a local copy of the variable we were passed.
    var test_parameter = event.data;
    
    // Do something...

    // Optionally reply to the message (Page A must also have
    // a 'message' event listener to receive this message).
    event.source.postMessage('Done!', 'https://example.org');

}, false);
D M
  • 5,769
  • 4
  • 12
  • 27
  • Doing this on a local server I keep getting: "Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('http://localhost:4210') does not match the recipient window's origin ('http://localhost:4200')." So does this mean it actually does not work cross origin? – Mickey Sly Jun 28 '22 at 14:35
  • It definitely works cross-origin. There are multiple reasons you might be getting that error; [here's a question](https://stackoverflow.com/questions/27573017/failed-to-execute-postmessage-on-domwindow-https-www-youtube-com-http) with some context and solutions. – D M Jun 28 '22 at 16:13
0

You can use in www.foo.com

var parameterValue = "something";
window.location = "www.bar.com?parameter="+parameterValue;

And in www.bar.com

var parUrl = window.location.search;
var urlParams = new URLSearchParams(parUrl);
var parameter = urlParams.get('parameter') // something
Stefino76
  • 369
  • 4
  • 10