- Открытие окон и методы window
- Блокировщик всплывающих окон
- Полный синтаксис window.open
- Доступ к новому окну
- How to Open a New Window In Javascript
- Opening a New Window
- Open New Window of Specified Height and Width
- Open a Window With No URL
- Make a link open a new window (not tab) [duplicate]
- 5 Answers 5
- HTML option
- JavaScript option
- Java Open a new window by clicking a button
- 2 Answers 2
- www.makeuseof.com
- Follow MUO
- How to Open Files/Folders With Only One Click in Windows
- How to Open Files/Folders With a Single Click
- Subscribe To Our Newsletter
- One More Step…!
Открытие окон и методы window
Материал на этой странице устарел, поэтому скрыт из оглавления сайта.
Более новая информация по этой теме находится на странице https://learn.javascript.ru/popup-windows.
Всплывающее окно («попап» – от англ. Popup window) – один из старейших способов показать пользователю ещё один документ.
В этой статье мы рассмотрим открытие окон и ряд тонких моментов, которые с этим связаны.
…При запуске откроется новое окно с указанным URL.
Большинство браузеров по умолчанию создают новую вкладку вместо отдельного окна, но чуть далее мы увидим, что можно и «заказать» именно окно.
Блокировщик всплывающих окон
Рекламные попапы очень надоели посетителям, аж со времён 20-го века, поэтому современные браузеры всплывающие окна обычно блокируют. При этом пользователь, конечно, может изменить настройки блокирования для конкретного сайта.
Всплывающее окно блокируется в том случае, если вызов window.open произошёл не в результате действия посетителя.
Как же браузер понимает – посетитель вызвал открытие окна или нет?
Для этого при работе скрипта он хранит внутренний «флаг», который говорит – инициировал посетитель выполнение или нет. Например, при клике на кнопку весь код, который выполнится в результате, включая вложенные вызовы, будет иметь флаг «инициировано посетителем» и попапы при этом разрешены.
А если код был на странице и выполнился автоматически при её загрузке – у него этого флага не будет. Попапы будут заблокированы.
Полный синтаксис window.open
Функция возвращает ссылку на объект window нового окна, либо null , если окно было заблокировано браузером.
url URL для загрузки в новое окно. name Имя нового окна. Может быть использовано в параметре target в формах. Если позднее вызвать window.open() с тем же именем, то браузеры (кроме IE) заменяют существующее окно на новое. params Строка с конфигурацией для нового окна. Состоит из параметров, перечисленных через запятую. Пробелов в ней быть не должно.
Значения параметров params .
- Настройки расположения окна:
left/top (число)
Координаты верхнего левого угла относительно экрана. Ограничение: новое окно не может быть позиционировано за пределами экрана.
Ширина/высота нового окна. Минимальные значения ограничены, так что невозможно создать невидимое окно с нулевыми размерами.
Если координаты и размеры не указаны, то обычно браузер открывает не окно, а новую вкладку.
- Свойства окна:
menubar (yes/no) Скрыть или показать строку меню браузера. toolbar (yes/no) Показать или скрыть панель навигации браузера (кнопки назад, вперёд, обновить страницу и остальные) в новом окне. location (yes/no) Показать/скрыть поле URL-адреса в новом окне. По умолчанию Firefox и IE не позволяют скрывать строку адреса. status (yes/no) Показать или скрыть строку состояния. С другой стороны, браузер может в принудительном порядке показать строку состояния. resizable (yes/no) Позволяет отключить возможность изменять размеры нового окна. Значение no обычно неудобно посетителям. scrollbars (yes/no) Разрешает убрать полосы прокрутки для нового окна. Значение no обычно неудобно посетителям.
- Ещё есть небольшое количество не кросс-браузерных свойств, которые обычно не используются. Вы можете узнать о них в документации, например MDN: window.open.
Браузер подходит к этим параметрам интеллектуально. Он может проигнорировать их часть или даже все, они скорее являются «пожеланиями», нежели «требованиями».
- Если при вызове open указан только первый параметр, параметр отсутствует, то используются параметры по умолчанию. Обычно при этом будет открыто не окно, а вкладка, что зачастую более удобно.
- Если указана строка с параметрами, но некоторые yes/no параметры отсутствуют, то браузер выставляет их в no . Поэтому убедитесь, что все нужные вам параметры выставлены в yes .
- Когда не указан top/left , то браузер откроет окно с небольшим смещением относительно левого верхнего угла последнего открытого окна.
- Если не указаны width/height , новое окно будет такого же размера, как последнее открытое.
Доступ к новому окну
Вызов window.open возвращает ссылку на новое окно. Она может быть использована для манипуляции свойствами окна, изменения URL, доступа к его переменным и т.п.
В примере ниже мы заполняем новое окно содержимым целиком из JavaScript:
How to Open a New Window In Javascript
In this article, we show how to open a create and open up a new window in javascript using the open() function.
The open() function is a function which allows a user to open a new window with Javasript.
Using this method, we can make a new window pop-up and be redirected to any URL we want. We can also determine the size of the window we create by specifying this in the parameters.
Below we create a variety of new windows with different parameters.
Opening a New Window
Again, we use the Javascript open() function to create a new window with Javascript.
The most simple format to open up a new window with Javascript is simply to specify the URL that this window will direct to, using the line:
where URL is the URL where you would like to redirect the user to.
This line above will open up a new window and be directed to the URL specified, http://www.dropbox.com.
We can attach this to a new button, using the following code:
This code above will create a button and will open up a new window to dropbox’s website when a user clicks on it.
This button is shown below. Click on it to see the effect of the above code:
Open New Window
This is the most basic way of using the window.open() function, where the only parameter you specify is the URL that you want the new window to direct to.
Open New Window of Specified Height and Width
Above is the most basic way of using the Javascript window.open() function. However, we can also specify additional parameters, in which we can choose the size which the new window opens to, both the height and the width.
Thus, the new window doesn’t have to be a full-size window. We can specify any height or width we want it to be.
If you press the button below, the window will open up with a width of 200 and a height of 200:
Open New Window
If you press the button below, the window will open up with a width of 600 and a height of 400:
Open New Window
Thus, you can see that you can choose the size dimensions that a new window will open with.
In order to specify height and width dimensions of a new window, the format to follow to do so are:
window.open(URL, name, ‘width=value, height=value‘);
The URL is the URL which the window will open up to. Name is the name of the new window which will be opened. Normally this field is kept blank. When kept blank, the URL will be the name that appears in the title bar of the new window. The width and height attributes specify the heigth and the width of the new window object.
So to create a new window that opens to the home page of http://google.com with a height of 600 and a width of 800, we use the code:
If placed in a button with an onclick event handler, the code would be:
This creates the following below:
Click to Go to Google
Open a Window With No URL
It’s also possible to open a blank web page, a web page which directs to no URL, if this is what is desired.
For example, you can open up to a blank page which maybe just displays a message on it, such as «This is My Web Page.»
Click the button below to see what is meant by this:
To create this, we create the button with an onclick event handler:
This button calls the openwindow() function when clicked on.
The Javascript code for this openwindow() function is:
In this Javascript code, we create a variable called newwindow which calls the function to open up a blank web page of width and height of 300 and stores the value and parameters of this window. Then we use this window object and write the line, «This is My Web Page» to it using the document.write() function.
So above are various ways of opening new windows with different parameters in Javascript.
Make a link open a new window (not tab) [duplicate]
Is there a way to make a link open a new browser window (not tab) without using javascript?
5 Answers 5
With pure HTML you can’t influence this — every modern browser (= the user) has complete control over this behavior because it has been misused a lot in the past.
HTML option
You can open a new window (HTML4) or a new browsing context (HTML5). Browsing context in modern browsers is mostly «new tab» instead of «new window». You have no influence on that, and you can’t «force» modern browsers to open a new window.
In order to do this, use the anchor element’s attribute target [1] . The value you are looking for is _blank [2] .
JavaScript option
Forcing a new window is possible via javascript — see Ievgen’s excellent answer below for a javascript solution.
(!) However, be aware, that opening windows via javascript (if not done in the onclick event from an anchor element) are subject to getting blocked by popup blockers!
[1] This attribute dates back to the times when browsers did not have tabs and using framesets was state of the art. In the meantime, the functionality of this attribute has slightly changed (see MDN Docu)
[2] There are some other values which do not make much sense anymore (because they were designed with framesets in mind) like _parent , _self or _top .
Java Open a new window by clicking a button
Been sitting here at my computer for about 13 hours and I think my eyes are bleeding. I found a little gui editor I love called GuiGenie. It works perfect for creating the window with the buttons and all that good stuff. The problem is i want to click a button in my first menu and have it open my other menu i made. I just starting programming 4 weeks ago so I’m a complete noob. I have a feeling its messing up because of the main methods but I have no idea and 13 hours of sitting here trying millions of things is making me go crazy : ) here is what i got so far
When the button is pressed, I want it to open this new window
If anyone could help I would appreciate it greatly!! I have a lot of respect for you pros out there because if you are a pro at this, you are probably smarter than 99.9% of the world. This stuff hurts my brain.
2 Answers 2
Here is something you can do, for this situation, where you have multiple Forms or Windows what you can do is to use a JPanel which can have this CardLayout set as it’s LayoutManager and then you can add the two JPanel s to it and access them with the methods provided by the same.
Don’t use setBounds() when using Absolute Positioning this is really not the right way of putting components to the parent container. Instead use setLocation(. ) and setSize(. ) methods. Consider not to use Absolute Positioning as much as possible for you. Certain lines in favour of the before said line taken from Java Docs are as follows :
Although it is possible to do without a layout manager, you should use a layout manager if at all possible. A layout manager makes it easier to adjust to look-and-feel-dependent component appearances, to different font sizes, to a container’s changing size, and to different locales. Layout managers also can be reused easily by other containers, as well as other programs.
Since the output of your program is really not a soothing experience in any sense. Atleast LayoutManager, can make that work a lot more easier for you, since you need not have to specify position and size for each and every component. Try walking through the Layout Mangers Tutorials, and get accustomed to them as soon as possible. They are the real life savers 🙂
Here is a modified code taken from your SOURCE CODE
www.makeuseof.com
Follow MUO
How to Open Files/Folders With Only One Click in Windows
Did you know there was a way to open files and folders with a single-click instead of a double-click?
Yes, we know opening files and folders on Windows isn’t a particularly taxing endeavor. A quick double-click and you’re in. If you struggle to double-click fast enough, you can change the speed by going to Settings > Devices > Mouse > Additional mouse options > Double Click Speed and adjusting the slider.
Or if you’re feeling adventurous, you could even right-click on the item and select Open from the context menu!
That’s all great, but did you know there was a way to open files and folders with a single click instead of a double click?
How to Open Files/Folders With a Single Click
To replace the traditional double-click with a single-click, follow these instructions:
- Open File Explorer and navigate to File > Change folder and search options.
- In the new window, click on the tab labeled General.
- Locate the section called Click items as follows.
- Mark the checkbox next to Single-click to open an item.
- Two previously grayed-out options will now be available below Single-click to open an item. Make sure you mark the checkbox next to Underline icon titles only when I point at them.
- When you’re happy with your setup, click Apply to save your changes.
If you ever want to return to double-clicks, just follow the above guide, but in Step 4, choose Double-click to open an item (single-click to select) instead.
Have you changed your system settings to open files and folders with a single-click instead? Did you find it easy to make the switch, or did you find yourself still double-clicking all the time?
You can leave your input, along with any questions about the process, in the comments below.
Image Credit: Pressmaster via Shutterstock
Looking for a way to monitor and protect your data from identity theft? Here are the best five services of 2021.
Dan joined MakeUseOf in 2014 and has been Partnerships Director since July 2020. Reach out to him for inquires about sponsored content, affiliate agreements, promotions, and any other forms of partnership. You can also find him roaming the show floor at CES in Las Vegas every year, say hi if you’re going. Prior to his writing career, he was a Financial Consultant.
Subscribe To Our Newsletter
Join our newsletter for tech tips, reviews, free ebooks, and exclusive deals!
One More Step…!
Please confirm your email address in the email we just sent you.