3

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?

1
  • You either need to post to a server script that enables CORS, or you have to put the value in a URL query parameter. Commented Feb 26, 2021 at 21:26

2 Answers 2

4

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Doing this on a local server I keep getting: "Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('localhost:4210') does not match the recipient window's origin ('localhost:4200')." So does this mean it actually does not work cross origin?
It definitely works cross-origin. There are multiple reasons you might be getting that error; here's a question with some context and solutions.
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.