最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How know if a window can be closed with js - Stack Overflow

programmeradmin1浏览0评论

So as it has been discussed elsewhere, a window can be closed by js using window.close() only if it has been opened by a script.

I have a page that offers a button to open a discussion window. The discussion window opens to a new tab with window.open(). The discussion page has a button that calls window.close(), which closes the discussion window and takes you back to previous tab, so you can continue from where you left off.

The problem is that if someone takes a the url directly to the discussion window, the close button does not work.

Is there a way to detect if the window will be closable with window.close(), so I can show the button only if it will work?

So as it has been discussed elsewhere, a window can be closed by js using window.close() only if it has been opened by a script.

I have a page that offers a button to open a discussion window. The discussion window opens to a new tab with window.open(). The discussion page has a button that calls window.close(), which closes the discussion window and takes you back to previous tab, so you can continue from where you left off.

The problem is that if someone takes a the url directly to the discussion window, the close button does not work.

Is there a way to detect if the window will be closable with window.close(), so I can show the button only if it will work?

Share Improve this question asked Jun 1, 2015 at 14:21 alianos-alianos- 91610 silver badges21 bronze badges 3
  • what does window.close do if it can't close the window? it might return undefined or give an error, you could check/catch that – atmd Commented Jun 1, 2015 at 14:23
  • I'm not totally sure, but I would assume that you could set var chat = window.open() when you open it form the button, and then set chat = null on close. if(chat !== null) then the window would have been opened via js – Seth McClaine Commented Jun 1, 2015 at 14:24
  • 1 @atmd I think the OP doesn't want to show the button if its not valid. – Seth McClaine Commented Jun 1, 2015 at 14:25
Add a comment  | 

2 Answers 2

Reset to default 16

You can check to see if window.opener is not null:

When a window is opened from another window, it maintains a reference to that first window as window.opener. If the current window has no opener, this method returns NULL. Windows Phone browser does not support window.opener. It is also not supported in IE if the opener is in a different security zone.

You can try using the window.opener object, which returns a reference to the window that opened the current window (if it's another window), or NULL if the current window was not opened via JS.

if (window.opener) //Show button
发布评论

评论列表(0)

  1. 暂无评论