问题
I have been researching this problem and while there's lots of posts on various forums about similar problems, none of the problems or solutions exactly match mine.
I have an application that has been successfully using the function below to redirect back to the parent window once finished with a popup. Recently I have been investigating compatibility with other browsers (to allow the system to be used via iPad) and have found that there is a problem with this function when using Safari or Chrome.
The parent page is a summary of some databased info, and the user clicks a link to open a window (via window.open) to view more detailed data. When finished there is a link on the child window that refreshes the data on the parent (partly to ensure the correct data is displayed when you return to the parent) and closes the child.
The Console in Safari reports "the result of 'window.opener.location.href' is not a function". I have tried to use the above and 'window.opener.document.location.href' and 'window.opener.window.location.href' (taken from other solutions offered up on the net) but with no success.
I know that some people have this function working well, while others have this sort of problem. I'm wondering if there are any answers to this specific situation.
Here is my function:
function quicklink(url) {
window.opener.document.location.href(url);
self.close();
}
This has worked from day one on IE7,8 and 9 but doesn't work in Safari (for windows or iPad) or Chrome.
Any ideas?
回答1:
href
is a property, not a method. Just assign the URL to it:
window.opener.document.location.href = url;
This will work in IE also. It's a property there too, even if it lets you use it as a method.
回答2:
Use below code to achieve desired results.
Parent:
<script language="javascript">
function open_a_window()
{
var w = 200;
var h = 200;
var left = Number((screen.width/2)-(w/2));
var tops = Number((screen.height/2)-(h/2));
window.open("window_to_close.html", '', 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width='+w+', height='+h+', top='+tops+', left='+left);
return false;
}
// opener:
window.onmessage = function (e) {
if (e.data === 'location') {
window.location.replace('https://www.google.com');
}
};
</script>
<input type="button" onclick="return open_a_window();" value="Open New Window/Tab" />
Popup:
<!DOCTYPE html>
<html>
<body onload="quitBox('quit');">
<h1>The window closer:</h1>
<input type="button" onclick="return quitBox('quit');" value="Close This Window/Tab" />
<script language="javascript">
function quitBox(cmd)
{
if (cmd=='quit')
{
window.opener.postMessage('location', '*');
window.open(location, '_self').close();
}
return false;
}
</script>
</body>
</html>
来源:https://stackoverflow.com/questions/7720061/window-opener-location-href-works-in-ie-but-not-chrome-or-safari