如何使用ASP.NET MVC和JavaScript关闭浏览器窗口

kzipqqlq  于 2022-12-14  发布在  .NET
关注(0)|答案(1)|浏览(188)

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

k97glaaz

k97glaaz1#

To avoid annoyances and bad practice, browsers disallow Javascript to close browser windows unless they detect a clear action to do so (i.e. 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.

相关问题