I have a script that create an iframe like this, and I use the iframe to check authentication then redirect the main window
:
var target "https://my.website.it"
var iframe = document.createElement("iframe");
iframe.id = "my-frame";
iframe.src = "/my-url/that?redirect=true&target=" + target
iframe.onload = function() {
iframeFn();
};
into the iframeFn()
function I want to check the location of the iframe itself to perform some controls before redirect:
function iframeFn() {
var myFrame = document.getElementById("my-frame");
var iframeWindow = myFrame.contentWindow;
if (iframeWindow.location.search.search(/fail/) >= 0) {
window.location = '/'
}
I put this script in a cdn and I use this script in a website with the same origin url of the redirect target (https://my.website.it
), and it works. But if I try to use this script in a website with different origin (https://different.website.it
) I got this error:
Uncaught DOMException: Blocked a frame with origin "https://different.website.it" from accessing a cross-origin frame.
at reloadInIFrame (https://static.website.it/my-script.js:34:29)
at HTMLIFrameElement.iframe.onload (https://static.website.it/.js:82:5)
at this line
if (iframeWindow.location.search.search(/fail/) >= 0) {
I've read this: SecurityError: Blocked a frame with origin from accessing a cross-origin frame but I can't figure out how to use window.postMessage
in my case.
NB: the second level domain is the same in both cases (website.it
)
Thanks for your help!