My application uses iframes to display content. I need to detect whether a page is loaded in an iframe. The problem is I need to do it with php, javascript manipulation of the DOM is not enough, I need to do something with php before page is loaded. I inject get parameters like inframe=1 on every anchor click inside the iframe, it works. But I can't find a good workaround for post requests. I tried with hidden input fields, but it doesn't work in my case, I don't have any control over it, since this application is a plugin for another.
The only workaround I have for post requests, is to check on iframe load, whether new location parameter contains 'inframe', if it doesn't then I add 'inframe' to the location and load the link again. It works, but page loads twice after form submits. I could hide the iframe on submit and show it after page is loaded second time, so it looks like it loaded once, but still loading it 2 times is noticeably slower and unacceptable as a solution.
So this is my not so good solution:
this.iframeReload = function($iframe) { //event listener for iframe load
var newSrc=$iframe.get(0).contentWindow.location.href;
if (newSrc.indexOf('inframe')==-1) {
console.log('redirecting');
if(newSrc.indexOf('?')==-1) href+='?inframe=1';
else newSrc+='&inframe=1';
$iframe.get(0).contentWindow.location=newSrc;
return 0; //terminate function and reload the iframe with parameter
}
$iframe.ready(function() { /*stuff to do after iframe loads*/ });
}
Is there a better way to do it? Like intercept the contentWindow.location change and add the parameter to it before even the page loads. I searched in Google and I only found to use load event, which I already use and it doesn't help much. Or maybe there is completely different solution? Any ideas appreciated. I spent almost 4 hours on things related to this problem.
Now after I've written it, mutation observer has come to my mind. I don't know much about it. Can it track contentWindow.location changes? I'm gonna try it.