jesse rurka
jesse rurka

Reputation: 31

Sending data from one domain to another using javascript (I have access to the <head> of both web pages)

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?

Upvotes: 3

Views: 4697

Answers (2)

Stefino76
Stefino76

Reputation: 369

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

Upvotes: 0

D M
D M

Reputation: 7179

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);

Upvotes: 4

Related Questions