Skip to main content

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โ€‹

APIChromeEdgeFirefoxSafariiOS SafariBaseline
Window.scrollToโœ… 1+โœ… 12+โœ… 1+โœ… 1+โœ… 1+Widely available
Window.openโœ… 1+โœ… 12+โœ… 1+โœ… 1+โ— partial 1+ [1]Limited
  1. 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; features is a string or { features?, noopener? }. Returns the new Window, or null if blocked or opened with noopener
  • closeWindow() โ€” closes the current window
  • focusWindow() โ€” focuses the current window
  • blurWindow() โ€” blurs the current window
  • scrollToTop(behavior?) โ€” scrolls to the top ('auto' or 'smooth')
  • scrollToBottom(behavior?) โ€” scrolls to document.body.scrollHeight
  • reloadWindow() โ€” reloads the current page
  • getWindowSize() โ€” { width, height } from innerWidth/innerHeight
  • onWindowResize(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.