1

my web page(mydomain.com/xyz.php) open in in both same & different origin. when it's open in same origin I update html of top window using jquery code which is inside xyz.php.

window.top.$("#idxzy").html(img_block);

all things is okay in same origin but when my web page open in different origin that time this line create error : xyz.php?product_id=XXXX Uncaught DOMException: Blocked a frame with origin "htt p s://www.mydomain.com/" from accessing a cross-origin frame.

window.top.$("#idxzy").html(img_block);

so I want to add condition here something like below but I don't know what should I use in if

if(same_origin){
    window.top.$("#idxzy").html(img_block);
}

also if I put console.log() for window.top.location. it's display something like below (same origin)

enter image description here

(not same origin) enter image description here

Sachin Sarola
  • 993
  • 1
  • 9
  • 26

2 Answers2

3

Use location.hostname:

if (location.hostname == "mydomain.com") {
    window.top.$("#idxzy").html(img_block);
}
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
1

You have to use Window.postMessage() to communicate between the iframe and the parent windows.

Here is the reference

Here you can find more info on that

You can also try catch to prevent the console error

try {
  if (location.hostname == "mydomain.com") {
     window.top.$("#idxzy").html(img_block);
   }
}
catch(err) {
  // Make sure you catch the exception thrown because is blocked by cross domain reference => then do 
}
dariogriffo
  • 4,148
  • 3
  • 17
  • 34