I have the below script on a page, let's say "child.html".
I only want the browser to see the function opener.opener = opener; opener.close()
if the referring URL is the one listed in the if
statement of the script (parent.html), otherwise I don't want the browser to see it.
The page that this script is on is a child page (a popup) of a parent page. Users (hopefully) will only access the parent page, which will subsequently open this child page and close the parent page at the same time using the opener.opener = opener; opener.close()
function.
The function works fine and does what I need it to do (closes the parent after opening the popup). But, if the child page URL is accessed directly (in other words without being directed from the parent page), then obviously there is no parent page to close and I get the script error:
'opener' is null or not an object
I understand the error message, hence why I'm trying to hide 'opener' if the referring URL IS NOT parent.html so that if someone happens to access the child page directly, opener is hidden and no error message.
What do I need to change in the below script to make this work?
<script type="text/javascript">
//<![CDATA[<!--
if (document.referrer != '../parent.html') {
opener.opener = opener;
opener.close();}
else {}
//-->
//]]>
</script>
Alternatively, I tried writing the following:
<script type="text/javascript">
//<![CDATA[<!--
if (document.referrer = '../parent.html') {
return false;
} else {
opener.opener = opener;
opener.close();}
//-->
//]]>
</script>
But that returns the script error: 'return' statement outside of function.
Thanks very much in advance for any help you can offer!
Your first script is correct if you put an AND
condition with the initialization of opener variable like:
if (document.referrer !== '../popup.html' && opener) { ... }
For the second one you have to write down a function if you want to use the return
statement like:
<script type="text/javascript">
//<![CDATA[<!--
function(){
function myFunct() {
if (document.referrer === '../parent.html' || !opener) {
return false;
} else {
opener.opener = opener;
opener.close();
return true;
}
}
myFunct();
}();
//-->
//]]>
</script>