Close browser with javascript

How to Close a Browser Tab/Window with JavaScript

I was asked by a visitor how he could close a browser window or tab using JavaScript. This article addresses that question.

Prerequisite

Since this was written in response to a JavaScript question, it assumes that you at least know how to insert JavaScript code into a web page.

How to Close a Window with JavaScript

To close a window or tab that was opened using JavaScript, call window.close() . For example, the following will close the current window/tab.

Note that window.close() will only work under the following conditions:

  1. On all modern browsers, the web page to be closed must be the first in that window/tab’s session history. That is, if you hit the Back button on the browser, you will not go to a previous page in that window/tab because there is none. You can easily accomplish that by opening that page either with JavaScript, for example, by using window.open() , or through a link that has a target=»_blank» attribute. You can find example code for the former in the demo below, and the latter in the article on opening links in a new window or tab. If you only test your code in an old browser (eg, old versions of Chrome or Firefox, or any version of Internet Explorer), you will end up with the mistaken impression that it works fine even if the above conditions are not true. Newer browser versions impose these restrictions for security (and other) reasons.
  2. Modern browsers will also resist your attempt to trick them into thinking that an existing window/tab was opened with JavaScript when it was not. Some older versions fell for such trickery, but these methods should no longer work in the current versions of Chrome and Firefox.
Читайте также:  Python tutor online compiler

Demo

Before you click the demo buttons below, please note the following:

  • The «Open demo» button will open a window/tab containing this very article, although the browser should automatically scroll to start of the demo section, since I linked directly to it. (See How to Link to a Specific Line or Paragraph on a Web Page Using HTML, if you want to do this.)
  • Although the «Close current window» button appears in both the original window/tab and the newly-opened demo, it may only work in the latter, depending on how you reached this article. If you are reading this in a modern browser, try it. That is, click the button in both the demo window (which should close) and this one (which may or may not). Having said that, you may not want to click the «Close current window» button on the original window in case you actually succeed, since you will then have to reload the page to continue reading.
  • Once again, be warned that the window that pops up is identical to the one you are reading (since it’s the same URL), with no visual cue to distinguish between the original and the demo. As such, if you don’t look at the list of tabs/windows in your browser after clicking, you may not realize that you are already looking at the demo. If you repeatedly click the «Open demo» button, thinking that nothing has happened, you will end up with multiple windows/tabs containing this article. That said, the «Close current window» button should work on all the tabs/windows except possibly the original one. And, of course, the usual way you close a tab in your browser will also work.
Читайте также:  Java windows api library

Open demo in a new window/tab Close current window if possible

Source Code for the Demo

The HTML code for the buttons is as follows:

It is just the standard HTML code for buttons, with the addition of onclick handlers that are invoked when someone clicks them.

The JavaScript for tsw_open_demo_window() , which is called when the «Open demo» button is clicked, is:

I used a relative URL here, since I’m just opening this same page, but you can use an absolute one (ie, a complete address, including the «http://» or «https://» portion) if you wish.

Since the «Close current window» button does nothing but call window.close() , I placed the JavaScript directly in its onclick attribute.

Copyright © 2019-2021 Christopher Heng. All rights reserved.
Get more free tips and articles like this, on web design, promotion, revenue and scripting, from https://www.thesitewizard.com/.

thesitewizard™ News Feed (RSS Site Feed)

Do you find this article useful? You can learn of new articles and scripts that are published on thesitewizard.com by subscribing to the RSS feed. Simply point your RSS feed reader or a browser that supports RSS feeds at https://www.thesitewizard.com/thesitewizard.xml. You can read more about how to subscribe to RSS site feeds from my RSS FAQ.

Please Do Not Reprint This Article

This article is copyrighted. Please do not reproduce or distribute this article in whole or part, in any form.

New Articles

It will appear on your page as:

Copyright © 2019-2021 Christopher Heng. All rights reserved.
thesitewizard™, thefreecountry™ and HowToHaven™ are trademarks of Christopher Heng.
This page was last updated on 21 April 2021.

Источник

Window: close() method

The Window.close() method closes the current window, or the window on which it was called.

This method can only be called on windows that were opened by a script using the Window.open() method, or on top-level windows that have a single history entry. If the window doesn’t match these requirements, an error similar to this one appears in the console: Scripts may not close windows that were not opened by script.

Note also that close() has no effect when called on Window objects returned by HTMLIFrameElement.contentWindow .

Syntax

Parameters

Return value

Examples

Closing a window opened with window.open()

This example shows a method which opens a window and a second one which closes the window; this demonstrates how to use Window.close() to close a window opened by calling window.open() .

//Global variable to store a reference to the opened window let openedWindow; function openWindow()  openedWindow = window.open("moreinfo.htm"); > function closeOpenedWindow()  openedWindow.close(); > 

Specifications

Browser compatibility

BCD tables only load in the browser

Found a content problem with this page?

This page was last modified on Apr 8, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

Как закрыть окно браузера с помощью JavaScript

Чтобы закрыть окно или вкладку браузера, которая была открыта с помощью JavaScript, используйте метод window.close(). Например, приведенный ниже код закроет текущую вкладку.

Метод window.close() будет работать только при следующих условиях:

  1. Вкладки должны быть открыты с помощью JavaScript. Например, с помощью open().
  2. В браузере Firefox вкладка, которую вы хотите закрыть, не должны быть открыты с помощью значений параметра strWindowFeatures «noopener» или «noreferrer». Например, если окно было открыто с помощью open(«index.html», «_blank», «noopener»), то функция window.close() не сработает.

Как закрыть окно браузера с помощью JavaScript — демонстрация

Обратите внимание на следующие особенности приведенного ниже примера:

  • Кнопка «Open demo» откроет вкладку с этой статьей. При этом браузер автоматически прокрутит страницу до начала раздела с демонстрацией.
  • Кнопка «Close current window» отображается как в текущей вкладке, так и во вновь открытой. Но она будет работать только в последней.
  • Если вы нажмете кнопку «Open demo» пару раз, то откроете несколько вкладок браузера с этой статьей. При этом кнопка «Close current window» должна работать во всех вкладках браузера. Но кроме оригинальной, которую вы открыли вручную.

Исходный код

  

Это стандартный HTML-код к с добавлением обработчиков onclick, которые вызываются, когда кто-то нажимает на кнопки.

JavaScript-функция tsw_open_demo_window()вызывается при нажатии кнопки «Открыть демонстрацию».

function tsw_open_demo_window()

Я использовал относительный URL-адрес, так как в примере открывается эта же страница. Но вы можете использовать абсолютный адрес (включая «http://» или «https://»).

Кнопка «Close current window» не выполняет никаких других действий, кроме вызова window.close(). Поэтому я поместил JavaScript-код непосредственно в ее атрибут onclick.

Вадим Дворников автор-переводчик статьи « How to Close a Browser Tab/Window with JavaScript »

Дайте знать, что вы думаете по этой теме статьи в комментариях. За комментарии, отклики, подписки, дизлайки, лайки низкий вам поклон!

Источник

Close browser with javascript

Learn Latest Tutorials

Splunk tutorial

SPSS tutorial

Swagger tutorial

T-SQL tutorial

Tumblr tutorial

React tutorial

Regex tutorial

Reinforcement learning tutorial

R Programming tutorial

RxJS tutorial

React Native tutorial

Python Design Patterns

Python Pillow tutorial

Python Turtle tutorial

Keras tutorial

Preparation

Aptitude

Logical Reasoning

Verbal Ability

Company Interview Questions

Artificial Intelligence

AWS Tutorial

Selenium tutorial

Cloud Computing

Hadoop tutorial

ReactJS Tutorial

Data Science Tutorial

Angular 7 Tutorial

Blockchain Tutorial

Git Tutorial

Machine Learning Tutorial

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures tutorial

DAA tutorial

Operating System

Computer Network tutorial

Compiler Design tutorial

Computer Organization and Architecture

Discrete Mathematics Tutorial

Ethical Hacking

Computer Graphics Tutorial

Software Engineering

html tutorial

Cyber Security tutorial

Automata Tutorial

C Language tutorial

C++ tutorial

Java tutorial

.Net Framework tutorial

Python tutorial

List of Programs

Control Systems tutorial

Data Mining Tutorial

Data Warehouse Tutorial

Javatpoint Services

JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.

  • Website Designing
  • Website Development
  • Java Development
  • PHP Development
  • WordPress
  • Graphic Designing
  • Logo
  • Digital Marketing
  • On Page and Off Page SEO
  • PPC
  • Content Development
  • Corporate Training
  • Classroom and Online Training
  • Data Entry

Training For College Campus

JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week

Like/Subscribe us for latest updates or newsletter RSS Feed Subscribe to Get Email Alerts Facebook Page Twitter Page YouTube Blog Page

Источник

Closing a Browser Window with JavaScript

Javascript Course - Mastering the Fundamentals

Sometimes it is needed to close a browser window that we opened, we can do this using javascript but due to security reasons, we can close only those browser windows that we opened using javascript script and not the windows that are opened by the user.

Introduction

The only thing to be noted here is that we can close only those browser windows that we opened using our javascript script/code. Today’s security standards do not allow closing the browser windows (using javascript script) that are opened by the user.

The below steps demonstrate the approach in which we open a URL using javascript so that it can be closed using the script :

  • Opening a new browser window using the javascript open method: First, it is needed to open a new browser window using the window.open() method. It takes two arguments, the first argument is the current URL which we will access through the location property of the window object and the second argument is the target URL which we will pass as _self because it makes the URL replace the current page.
  • Closing this opened window using the javascript close method: Since we opened the new browser window using the javascript script therefore we can close it using the window.close() method. This method does not any argument and it closes the window on which it is called.

JavaScript Program to Close a Browser Window Using window.close() Method

The below program demonstrates the approach we discussed above.

output-close-browser-window-using-method

Explanation: First, we created an HTML document and under the body tag, we defined an h1 heading tag that displays Hello World!! and also we have defined a paragraph tag that says to click the button to close the window. Then we have defined the button and attached on click listener to it which defines what happens when the button is clicked. At last, we have the javascript script which defines the functionality of the above-defined function. The script contains a function in which we have defined a variable my_window and opened the new window, then we closed the current window using the close() method.

Conclusion

  • To close a browser window we can use the javascript close method but we can use this method only when we have opened a new browser window using code.
  • Due to modern security reasons, we cannot close a browser window that is opened by the user.
  • To Open a new browser window we use the javascript open() method.
  • To close this browser window we use the javascript close method.

Источник

Оцените статью