简体   繁体   中英

How to close browser window using Asp.Net MVC and JavaScript

I want to close window tab after some success action, because customer don't want to close it manually

Script below

<script type="text/javascript">
    window.close()
<script>

closes only the current View(), not the whole window. But if it places in "_Layout.cshtml" at the first start the script is processed as expected. But after several redirects, and then when returning to "index.cshtml", an error appears

Scripts may close only the windows that were opened by them.

I know this is javascript defensive constraint, but I'm not good with js, and I don't know in which case this error appears and how to bypass or avoid it

To avoid annoyances and bad practice, browsers disallow Javascript to close browser windows unless they detect a clear action to do so (ie the result of a button press). If you're looking to close the window after some async work, its very likely you won't be able to do so.

You should try adding a popup window that gives the user the option to click a button which will close the tab if that is enough. You can add the following to the button to make it do so:

onClick="window.close()"

and it should work just fine. Failing that, try using an a tag like

<a href="javascript:close_window();">Close</a>

If you absolutely can not live without this feature, you'll need to create an extension for each browser you want to support that will close the window upon request. Beyond that, you'll need to find an exploit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM