- porthole.js — how can I close a tab that I opened using window.open(), but from the new tab
- 2 Answers 2
- Why Were The Port Hole Windows Opened
- Aaron Quirey
- Dave Gittins
- Aaron Quirey
- Michael H. Standart
- Steven Hall
- Samuel Halpern
- Jim Kalafus
- Ioannis Georgiou
- Steven Hall
- Adam Francis
- Augusto Félix Solari
- Michael H. Standart
- Bob Godfrey
- Augusto Félix Solari
- Bob Godfrey
- Augusto Félix Solari
- monica e. hall
- Bob Godfrey
- Jim Currie
- Форум
- Справочник
- window.open
- Синтаксис
- Аргументы
- Описание, примеры
- Связь между окнами
- Строка параметров
- Основные кроссбраузерные параметры
- Porthole
- Contents
- Etymology [ edit ]
- Structure [ edit ]
- Spacecraft portholes [ edit ]
- Submarine portholes [ edit ]
porthole.js — how can I close a tab that I opened using window.open(), but from the new tab
I need to spawn a tab using window.open(‘. ‘, ‘_blank’);
Then, I need that tab to CLOSE ITSELF, when the user click a button (button is in the new tab).
I have control over the codebase and server of both applications.
I tried the following:
Unfortunately I get security exception: Error: Blocked a frame with origin «http://localhost:5007» from accessing a cross-origin frame.
How can I get around this error? Is there anyway I can use this library to overcome this? https://github.com/ternarylabs/porthole
2 Answers 2
I am simply going to quote documentation here, just for anyone who needs a reference click W3C and MDN.
To break it down, the open and close functions use parameters than can be very useful, such as the URL , when desiring to open or close the current window, or in your case the opened window.
A practical example would be this stack overflow question. N
I hope it helps!
EDIT
To answer the OP’s edit to the question: If it is a matter of triggering an event on a window which was opened, you can on the new window have an event handler which will trigger window.close() like so:
However, if you truly do have control over the new tab, because it leads to a URL whose code base you are in control of, then it is only a matter of triggering an event there that you can trigger either once the window loads, or once you click a button. like so:
EDIT #2
To further extend the OP’s edit, I want to include here an issue that can easily be encountered when attempting to trigger the opened window to close itself.
Scripts are not allowed to close a window that a user opened. This is considered a security risk. Though it isn’t in any standard, all browser vendors follow this (Mozilla docs). If this happens in some browsers, it’s a security bug that (ideally) gets patched very quickly.
None of the hacks in the answers on this question work any longer, and if someone would come up with another dirty hack, eventually it will stop working as well.
I suggest you don’t waste energy fighting this and embrace the method that the browser so helpfully gives you — ask the user before you seemingly crash their page.
In other words, unless your webpage’s script has control of the window which was opened, you should/cannot close said window. That is because the script running the window.close is not in control of the opened window.
EDIT #3
So many edits I know! But I am answering this in between my daily routine so bear with me. To answer the porthole.js question, it should be much more possible to do something with it, however you need to realize that you are working with iframes.
There is a significant difference when working with websites vs working with iframes, in which iframes are Widgets and websites (including mini sites) are given a URL. There are lots of considerations as well in terms of security and sandboxing, as can be seen on the portholejs demo here. This difference is also what does not allow you to work with different websites the way you want to initially.
My advise would be to evaluate your options with respect to your implementation: website to website vs website to widget.
Why Were The Port Hole Windows Opened
Aaron Quirey
Why were the port hole windows open during the sinking? Was it the terrible smell of paint? and could this have caused the ship to list more to port?
Testimony from Survivor Emily Ryerson
(First Class Passenger)
— She left Titanic on one of the last port side lifeboats at 1.50am
Q. When you went down into the water, from the boat, did you notice anything about the portholes in the side of the ship?
A. Yes, a great many were open.
Q. Did you notice anything in particular about the portholes on the water?
A. Yes, the water was washing in the portholes. You could see far inside the cabins and see the water washing in and around the gold furniture and decorations. It was brilliantly lighted, which deck I could not tell.
Q. Did you notice any of the lines of portholes disappear after you got in the boat?
A. Yes, she was sinking very rapidly then, we saw two lines and then we saw only one.
Dave Gittins
Aaron Quirey
She gave further evidence to the inquiry. See below.
Michael H. Standart
Steven Hall
Samuel Halpern
Jim Kalafus
>Again, people may have just opened them to have a look out side.
Could the portholes simply be swung open? I thought that there were tools needed. Maxtone-Graham mentions a common injury to passengers’ knuckles, which would occur when they tried to re-open portholes that had been secured for the night by stewards.
Ioannis Georgiou
So far as I remember it were the windows on B Deck as they were also described by Mrs Stephenson and Miss Eustis who report about water on the deck with square windows. Both were in the same boat (No. 4) as Mrs Ryerson.
Sure more were open also on the other decks.
Steven Hall
«Steve, weren’t some of the port holes on the ship constructed to allow fresh air to come in but automatically seal closed if the sea rose to cover them?»
I believe there were. I’ll check about that tonight. But there was a simple locking device I believe that kept them open.
I’ll look into the Britannic also.
Adam Francis
Might it have had something to do with ventilators being shut down? I seem to remember something to that effect, but I thought it was in reference to the boiler and engine rooms.
It would appear the heaters were functional during the sinking, if it were hot wouldn’t they shut off the heaters in their staterooms?
Just seems that it must have had something to do with a lack of air circulation, with as many people milling and wandering around inside it probably got warm especially to those wearing heavy clothing to keep them warm.
Augusto Félix Solari
Michael H. Standart
Bob Godfrey
Augusto Félix Solari
Bob Godfrey
Augusto Félix Solari
monica e. hall
I expect people’s window open-or-shut preferences were merely about their own experiences. Yes, Bob, our grannies thought fresh air was good, but they never experienced cholera epidemics — the deadly «miasma». On balance, though, I think people in 1912 though fresh air was good, for obvious reasons. Well, obvious to them. Stuffy, smelly atmospheres could spell disease, no matter how science was already explaining contagion. So you’d be tucked up in bed with the porthole open, most probably. And the better-educated you were, the more you were likely to subscribe to the open-porthole theory.
I’ve no idea really. But my granny, who was in her teens in 1912, certainly thought that fresh air was mandatory all her life.
Neither she, nor my other granny, cared much about the Titanic, which is odd since it happened in their lifetime. But they did care about ventilation and their own children.
Bob Godfrey
Jim Currie
There was nothing really odd about the older generation’s silence concerning Titanic. They had two World Wars and a recession to occupy their minds.
My Mother and father were the youngest of their families when Titanic went down. I never heard them, my grandfather or any of my 8 aunts or 8 uncles (4who served in WW1) ever mention Titanic until I went to sea school 38 years after the event. Then it was in the form of a joke. ‘hope you don’t sail on Titanic!’
When I did go to sea.. everyone, including passengers, kept their port holes open at sea. For all kinds of reasons. Not the least of which being; it might be the only route left to you in the event of a collision, a fire or if the ship rolled over. There was the fresh air thing too.
Most ships did not have AC until the early 60s. The modern ones before then had what they called punkha-louvres.. modern aircraft have similar little blowers mounted over every seat. In most cases; depending where your cabin was relative to the sea and spray, the port glass was lowered onto the port hole securing lugs or’dogs’. These normally swivelled into position after the porthole was closed, securing it tight against rubber seals. However, if the ‘dogs’ were swivelled into the port hole aperture before closing the port, they prevented it from closing fully, leaving an inch or so gap. Thus you could get fresh air without wind driven rain or spray. The only time I ever closed my porthole was when in port to stop thieving ba. s stealing the few things I owned. That would never happen at sea!
In the many years I was at sea, I cannot recall a discussion about Titanic. Sailors did not tend to talk about these things. Even although most of those I knew had had a ship shot from under them at least once. I will no doubt make myself even more unpopular by observing that Titanic OCD (Obsessive Compulsive Disorder) is almost entirely a land-based affliction to which I, Unfortunately or otherwise have been smitten. That said; I enjoy my ‘illness’.
Форум
Справочник
window.open
Синтаксис
Аргументы
Описание, примеры
Метод open создает новое окно браузера , аналогично команде «Новое окно» в меню браузера. Обычно это не вкладка, а именно новое окно, но в некоторых браузерах можно настроить то или иное поведение явным образом.
Если параметр strUrl — пустая строка, то в окно будет загружен пустой ресурс about:blank.
В любом случае, загрузка осуществляется асинхронно. Создается пустое окно, загрузка ресурса в которое начнется уже после завершения исполнения текущего блока кода.
Связь между окнами
Метод open возвращает ссылку на новое окно, которая служит для обращения к нему и вызову его методов, если это соответствует ограничениям безопасности Same Origin.
Если окно с именем winName уже существует, то вместо открытия нового окна, strUrl загружается в существующее, ссылка на которое возвращается. При этом строка параметров не применяется.
В случае, когда окно открыть не удалось, например, оно заблокировано штатными Popup-blocker’ами Firefox/IE — вызов open вернет null.
Проверяйте его, если не хотите лишних ошибок в своих скриптах.
Указание пустого strUrl для существующего имени окна — удобный способ получить ссылку на это окно без его перезагрузки.
Если вы хотите открывать новое окно при каждом вызове open() — используйте для winName специальное значение ‘_blank’.
Строка параметров
Необязательная строка параметров состоит из списка разделенных запятой настроек нового окна. После открытия окна их уже нельзя будет изменить.
Если строки параметров нет или она пустая, то для нового окна будут взяты параметры по умолчанию.
Если строка параметров указана, то не перечисленные в ней параметры будут отключены(кроме titlebar/close). Поэтому включите в ней свойства, которые нужны.
Если в параметрах не указаны размеры, то новое окно будет по размеру такое же, как последнее открытое.
Если не указана позиция нового окна, то оно откроется со сдвигом в 20-30 пикселей (зависит от браузера) от последнего открытого окна.
Такой сдвиг позволяет посетителю заметить, что открылось новое окно.
Если текущее окно максимизировано, то сдвига не будет: новое тоже будет максимизировано.
Основные кроссбраузерные параметры
Параметры, касающиеся элементов управления окна, могут быть жестко установлены в конфигурации браузера. В этом случае их указание в параметрах open() не даст нужного эффекта.
left/top Расстояние от левой/верхней границы окна операционной системы до границы нового окна. Новое окно не может быть создано за границами экрана height/width Высота/ширина в пикселях внутренности нового окна, включая полосы прокрутки, если они есть. Минимальное значение: 100 menubar Если этот параметр установлен в yes, то в новом окне будет меню. toolbar Если этот параметр установлен в yes, то в новом окне будет навигация (кнопки назад, вперед и т.п.) и панель вкладок location Если этот параметр установлен в yes, то в новом окне будет адресная строка directories Если этот параметр установлен в yes, то в новом окне будут закладки/избранное status Если этот параметр установлен в yes, то в новом окне будет строка состояния resizable Если этот параметр установлен в yes, то пользователь сможет изменить размеры нового окна. Рекомендуется всегда устанавливать этот параметр. scrollbars Если этот параметр установлен в yes, то новое окно при необходимости сможет показывать полосы прокрутки
Porthole
From Wikipedia the free encyclopedia
A porthole, sometimes called bull’s-eye window or bull’s-eye, [1] is a generally circular window used on the hull of ships to admit light and air. Though the term is of maritime origin, it is also used to describe round windows on armored vehicles, aircraft, automobiles (the Ford Thunderbird a notable example) and even spacecraft.
On a ship, the function of a porthole, when open, is to permit light and fresh air to enter the dark and often damp below-deck quarters of the vessel. It also affords below-deck occupants a limited view to the outside world. [2] When closed, the porthole provides a strong water-tight, weather-tight and sometimes light-tight barrier.
A porthole on a ship may also be called a sidescuttle or side scuttle (side hole), as officially termed in the International Convention for the Safety of Life at Sea. This term is used in the U.S. Code of Federal Regulations. [3] It is also used in related rules and regulations for the construction of ships. [4] The use of the word «sidescuttle» instead of «porthole» is meant to be broad, including any covered or uncovered hole in the side of the vessel.
Contents
Etymology [ edit ]
According to the Navy Department Library, the word «porthole» has nothing to do with its location on the port side of a ship, but originated during the reign of Henry VII of England (1485). The king insisted on mounting guns too large for his ships and therefore the conventional methods of securing the weapons on the forecastle and aftcastle could not be used. A French shipbuilder named James Baker was commissioned to solve the problem, which he did by piercing the ship’s sides so the cannon could be mounted inside the fore and aft castles. For heavy weather and when the cannons were not in use, the openings were fitted with covers, that were called porte in French, meaning «door». «Porte» was Anglicized to «port» and later corrupted to porthole. Eventually, it came to mean any opening in a ship’s side whether for cannon or not. [5]
Structure [ edit ]
A porthole consists of at least two structural components and is, in its simplest form, similar to any other type of window in design and purpose. The porthole is primarily a circular glass disk, known as a ‘portlight’, encased in a metal frame that is bolted securely into the side of a ship’s hull. Sometimes the glass disk of a porthole is encased in a separate frame which is hinged onto the base frame so that it can be opened and closed. In addition, many portholes also have metal storm covers that can be securely fastened against the window when necessary. The main purpose of the storm cover is, as its name implies, to protect the window from heavy seas. It is also used to block light from entering lower berths when darkness is preferred. The storm cover is referred to as a deadlight in maritime parlance. [6] Storm covers are also used on navy and merchant marine ships to prevent interior light from escaping the ship’s lower berths, and to provide protection from hostile fire. Hinged porthole windows and storm covers are accessible from inside the ship’s hull, and are typically fastened to their closed positions by hand tightening several pivoting, threaded devices, commonly referred to as «dogs». Older portholes can be identified by the protruding collar of their base plate which may be up to several inches deep, thus accommodating the thickness of a wooden hull.
Portholes range in diameter from several inches to more than two feet, and weigh from several pounds to over one hundred pounds. Much of the porthole’s weight comes from its glass, which, on ships, can be as much as two inches thick. Metal components of a porthole are also typically very heavy; they are usually sand-cast and made of bronze, brass, steel, iron, or aluminium. Bronze and brass are most commonly used, favoured for their resistance to saltwater corrosion. The design of the porthole is such that it achieves its humble purposes without sacrificing the integrity of the ship’s hull. The porthole’s thick glass and rugged construction, tightly spaced fasteners, indeed even its round shape, all contribute to its purpose of maintaining hull strength and withstanding the pressure of storm waves crashing against it.
Recently there has been a decline in the number of portholes on larger ships. Cruise liners have higher superstructures with more upper deck cabins which can have large windows and balconies. Most warships no longer have portholes on their main hulls as they could weaken them and modern vessels have air conditioning and strong lighting below decks meaning that they are no longer necessary. [7]
Spacecraft portholes [ edit ]
Portholes on spacecraft must be made from glass that can survive rapid temperature changes, without suffering the cracking that can result from thermal shock. Those on the International Space Station were made from quartz glass mounted on titanium frames, covered with enamel. These are not designed to be opened. The windows also have shrouds or doors to protect them from micro-meteorites. [8]
On the Apollo space capsules a porthole was located in the hatch that the astronauts used at the beginning and end of each flight.
Submarine portholes [ edit ]
Portholes on submarines are generally made of acrylic plastic. In the case of deep diving submarines, the portholes can be several inches thick. The edge of the acrylic is usually conically tapered such that the external pressure forces the acrylic window against the seat. Usually such windows are flat rather than spherically dished. This decreases the area that can be viewed, but eliminates distortion associated with curved glass.