Reputation: 10592
I have an iFrame which contain an anchor with target="_blank"
. I wish to run some JavaScript in the iFrame after the new window has opened.
I tried using setTimeout(/*my js to run*/, 0)
in the onclick
event of the anchor. It works in Chrome but not in Firefox. Putting a 100 ms delay in the setTimeout seems to fix this issue with Firefox, but this solution does not look very clean.
Is there a standard way to run js code after a link was opened in a new window?
edit some clarifications: the js I want to run triggers a page refresh. If I put it directly in the onclick event, the anchor link is not opened because the onclick event happens before. This is why I need to run the js code after the new window has opened.
second edit I have access to the first page and the popup, but not to the target of the link.
Upvotes: 1
Views: 740
Reputation: 178422
If you need to refresh AND open a link in a new window you do want setTimeout like this
Inline:
<a href="popup.html" target="_blank"
onclick="setTimeout(function() { location.reload(1);},10)">Click</a>
Better:
<a href="popup.html" id="pop" target="_blank">Click</a>
using
function reload() {
setTimeout(function() { location.reload(1);},10);
}
window.onload=function() {
document.getElementbyId("pop").onclick=reload;
}
Do you have access to the page in the popup and is it the same origin as the iFrame and is it the same origin as the parent page? Then you can use the onload event of the popped page:
window.onload=function() { opener.reload(1); }
Upvotes: 1
Reputation: 10902
Add an onReady or onLoad hook into the page that's loading. Then, "after the new window has opened" the JavaScript will be run. If you need to affect the parent window then use window.opener
in the JavaScript in the popup.
Upvotes: 0