I have an html button that I want to close the current window when clicked. I thought I could just set the onclick feature like I did below. Am I missing something?
This should do it. In order to close it your page needs to be opened by the script, hence the window.open. Here is an article explaining this in detail:
If all else fails, you should also add a message asking the user to manually close the window, as there is no cross-browser solution for this, especially with older browsers such as IE 8.
JavaScript can only close a window that was opened using JavaScript. Example below:
JavaScript只能关闭使用JavaScript打开的窗口。示例如下:
<script> function myFunction() { var str = "Sample"; var result = str.link("https://sample.com"); document.getElementById("demo").innerHTML = result; } </script>
Use the code below. It works every time.
使用下面的代码。每次都很管用。
<button onclick="self.close()">Close</button>
It works every time in Chrome and also works on Firefox.
它每次都能在Chrome上运行,也能在Firefox上运行。
Closing a window that was opened by the user through JavaScript is considered to be a security risk, thus not all browsers will allow this (which is why all solutions are hacks/workarounds). Browsers that are steadily maintained remove these types of hacks, and solutions that work one day may be broken the next.
< input type="button" value="Close this window" onclick="self.close()">
I know this thread has been answered, but another solution that may be useful for some, particularly to those with multiple pages where they want to have this button, is to give the input an id and place the code in a JavaScript file. You can then place the code for the button on multiple pages, taking up less space in your code.
Thanks that is good advice but the actual problem is that I'm a moron. Wasted tons of time because I was testing a different file from the one I was editing. Wow... Thanks for the good advice though!
nice... I'll have to use this next time I have to write a script that creates 130 new windows
不错...下次我写脚本创建130个新窗口的时候,
Well that sure seems to circumvent the entire point of not allowing a raw window.close() call...
这似乎完全绕过了不允许原始window.lose()调用的全部要点...
Doesn't work for me in Chrome 72.0.3626.121, 64-bit. Also, to note, the linked article uses _parent instead of _self. But neither worked per my testing on a local development page -- when the page was opened directly in Chrome, not via script or link from another page. However, works in Edge! :) But window.close() alone also works -- with a confirmation.
'but the actual problem is that I'm a moron.' - hilarious - we have all been there brother!
“但真正的问题是我是个白痴。”--搞笑--兄弟,我们都有过这样的经历!
Anecdotal evidence and personal assurances don't make for a better answer. Besides, this script will be prevented from running wherever the page wasn't opened by another script.
传闻证据和个人保证并不能提供更好的答案。此外,此脚本将被阻止运行的页面没有被另一个脚本打开。
Scripts may close only the windows that were opened by them. is what I get doing either of those. In Chrome console.
我是一名优秀的程序员,十分优秀!