I have request from the customer to adjust some old functionality in the system. The current file has href links that look like this:

<a href="page_detail.cfm?id=#id#" target="_blank">#Name#</a>

If you look the code above you see that target="_blank" page will be opened in the new browser window. However, user wants to be able to close that window if they click OK/Cancel button in page.detail.cfm. I tried using this code for closing the browser window:

var closeBtn = document.getElementById('btn_cancel');
closeBtn.addEventListener('click', cancel);
function cancel(){
    window.close();
}

After I tested the code and clicked Cancel message in the dev tools looks like this:

Scripts may not close windows that were not opened by script.

I guess that window can't be closed if not previously opened with JavaScript. I'm not sure what would be the best approach to solve this issue? Thanks for your help.

1 Answers

-1
Michael Cacciano On

Technically a script is not allowed to close a page that a user has opened as opposed to it being opened by a script itself. It's a browser security issue. I know there were some hacks for it but thing like this get patched pretty quick from what I can tell. You could technically open the window with a script instead with some sort of click event or such, but again this is a bit of a work around. Check this out https://developer.mozilla.org/en-US/docs/Web/API/Window/close