window
Small wrappers around common window operations โ opening/closing/focusing
windows, scrolling, reloading, and reading or watching viewport size.
Import: @rtorcato/browser-common/window
๐ MDN: Window
Browser supportโ
| API | Chrome | Edge | Firefox | Safari | iOS Safari | Baseline |
|---|---|---|---|---|---|---|
Window.scrollTo | โ 1+ | โ 12+ | โ 1+ | โ 1+ | โ 1+ | Widely available |
Window.open | โ 1+ | โ 12+ | โ 1+ | โ 1+ | โ partial 1+ [1] | Limited |
- iOS Safari: This method will not function if the target parameter is unspecified or set to _blank.
โ
supported ยท โ partial ยท โ not supported ยท [n] see note. Generated from MDN browser-compat-data and web-features. caniuse: Window.scrollTo ยท Window.open
Exampleโ
import {
openWindow,
closeWindow,
focusWindow,
blurWindow,
scrollToTop,
scrollToBottom,
reloadWindow,
getWindowSize,
onWindowResize,
} from '@rtorcato/browser-common/window'
openWindow('https://example.com', '_blank', { noopener: true })
scrollToTop('smooth')
const { width, height } = getWindowSize()
const off = onWindowResize(() => console.log(window.innerWidth))
off()
Exportsโ
openWindow(url, target?, features?)โwindow.open;featuresis a string or{ features?, noopener? }. Returns the newWindow, ornullif blocked or opened withnoopenercloseWindow()โ closes the current windowfocusWindow()โ focuses the current windowblurWindow()โ blurs the current windowscrollToTop(behavior?)โ scrolls to the top ('auto'or'smooth')scrollToBottom(behavior?)โ scrolls todocument.body.scrollHeightreloadWindow()โ reloads the current pagegetWindowSize()โ{ width, height }frominnerWidth/innerHeightonWindowResize(callback)โ subscribe to resize; returns an unsubscribe function
Safe usageโ
Unlike <a target="_blank">, window.open does not imply noopener. By default the
opened page gets window.opener and can navigate this page (reverse tabnabbing). When the URL
is not fully trusted, opt in:
openWindow(userSuppliedUrl, '_blank', { noopener: true })
This passes noopener,noreferrer. The browser then returns null even when the window
opens, so don't use the return value to detect a blocked popup in this mode.
โ ๏ธ noopener does not validate URL schemes. A javascript: or data: URL will still
be opened even with noopener set. For untrusted URLs, validate the scheme first:
const url = userSuppliedUrl
const isHttpsUrl = /^https?:\/\//.test(url)
if (isHttpsUrl) {
openWindow(url, '_blank', { noopener: true })
}
See the API reference for full signatures.