1

I have a React.js app and it displays inside a html iframe. How would I pass the URL params queries inside so my React app can access them. I tried to research online but couldn't find a solution for React. See code below and the solutions I tried. I get error message like TypeError: iframe is null. etc..

URL

 http://website.com?param1=myname&param1=lastname

HTML iFrame

 <iframe id="myIframe" src="http://localhost:3000/myReactApp" frameborder="0">

React.JS => index.js My first try

var loc = window.location.toString(),
    params = loc.split('?')[1],
    iframe = document.getElementById('myIframe');

iframe.src = iframe.src + '?' + params;​​​​​​​​​​​​​​​​
console.log(iframe.src);

My second try in React.JS app

(function() {
var frameBaseSRC = document.getElementById("myIframe").src;
var frameQueryString = document.location.href.split("iFrameQuery=")[1];
 if (frameQueryString != undefined) {
  document.getElementById("myIframe").src = frameBaseSRC + "?q=" + frameQueryString;
 }
})();
icode
  • 637
  • 2
  • 10
  • 22

3 Answers3

1

I got it working! Using code below. I got the code from here How to pass parameters through iframe from parent html?

let getParamValue = function(paramName)
{
    var url = window.location.search.substring(1); //get rid of "?" in querystring
    var qArray = url.split('&'); //get key-value pairs
    for (var i = 0; i < qArray.length; i++) 
    {
        var pArr = qArray[i].split('='); //split key and value
        if (pArr[0] === paramName) 
           console.log(pArr[1]);
            return pArr[1]; //return value
    }
}

getParamValue('param1');
Community
  • 1
  • 1
icode
  • 637
  • 2
  • 10
  • 22
0

In this example the iframe and parent document are in separate domains so the URL would not be accessible.

If they iframe and parent document are hosted in same URL you should be able to do window.parent.location

Ivo
  • 535
  • 2
  • 13
0

window.location.ancestorOrigins

does gives the ancestors of the component. If a react component or page is inserted in an iframe where the webpage host(page in iframe) and the browser link(main host), this returns a lists of hostnames by which the iframe page is being rendered.

koka
  • 1
  • 1