Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
560 views
in Technique[技术] by (71.8m points)

javascript - 如何关闭浏览器窗口中的当前选项卡?(How to close current tab in a browser window?)

I want to create a link on a webpage that would close the currently active tab in a browser without closing other tabs in the browser.

(我想在网页上创建一个链接,该链接将关闭浏览器中当前处于活动状态的标签,而不关闭浏览器中的其他标签。)
When the user clicks the close link, an alert message should appear asking the user to confirm with two buttons, "YES" and "NO".

(当用户单击关闭链接时,将出现一条警告消息,要求用户使用两个按钮“是”和“否”进行确认。)

If the user clicks "YES", close that page and If "NO", do nothing.

(如果用户单击“是”,则关闭该页面,如果“否”,则不执行任何操作。)

How can it be done?

(如何做呢?)

Any suggestions?

(有什么建议么?)

  ask by Naveed translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You will need Javascript to do this.

(您将需要Javascript来执行此操作。)

Use window.close() :

(使用window.close() :)

close();

Note: the current tab is implied.

(注意:隐含当前选项卡。)

This is equivalent:

(这等效于:)

window.close();

or you can specify a different window.

(或者您可以指定其他窗口。)

So:

(所以:)

function close_window() {
  if (confirm("Close Window?")) {
    close();
  }
}

with HTML:

(使用HTML:)

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

or:

(要么:)

<a href="#" onclick="close_window();return false;">close</a>

You return false here to prevent the default behavior for the event.

(您在此处return false以防止事件的默认行为。)

Otherwise the browser will attempt to go to that URL (which it obviously isn't).

(否则,浏览器将尝试转到该URL(显然不是)。)

Now the options on the window.confirm() dialog box will be OK and Cancel (not Yes and No).

(现在, window.confirm()对话框上的选项将为“确定”和“取消”(不是“是”和“否”)。)

If you really want Yes and No you'll need to create some kind of modal Javascript dialog box.

(如果您确实想要“是”和“否”,则需要创建某种模式的Javascript对话框。)

Note: there is browser-specific differences with the above.

(注意:上述内容与浏览器特定。)

If you opened the window with Javascript (via window.open() ) then you are allowed to close the window with javascript.

(如果使用Javascript打开窗口(通过window.open() ),则可以使用javascript关闭窗口。)

Firefox disallows you from closing other windows.

(Firefox不允许您关闭其他窗口。)

I believe IE will ask the user for confirmation.

(我相信IE会要求用户确认。)

Other browsers may vary.

(其他浏览器可能会有所不同。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...