chrome.offscreen

Description

Use theoffscreen API to create and manage offscreen documents.

Permissions

offscreen

To use the Offscreen API, declare the"offscreen" permission in theextension manifest. For example:

{"name":"My extension",..."permissions":["offscreen"],...}

Availability

Chrome 109+MV3+

Concepts and usage

Service workers don't have DOM access, and many websites have content security policies thatlimit the functionality of content scripts. The Offscreen API allows the extension to use DOMAPIs in a hidden document without interrupting the user experience by opening new windows ortabs. Theruntime API is the only extensions APIsupported by offscreen documents.

Pages loaded as offscreen documents are handled differently from other types of extension pages.The extension's permissions carry over to offscreen documents, but with limits on extension APIaccess. For example, because thechrome.runtime API is the onlyextensions API supported by offscreen documents, messaging must be handledusing members of that API.

The following are other ways offscreen documents behave differently from normal pages:

  • An offscreen document's URL must be a static HTML file bundled with the extension.
  • Offscreen documents can't be focused.
  • An offscreen document is an instance ofwindow, but the value of itsopener property is alwaysnull.
  • Though an extension package can contain multiple offscreen documents, an installed extension can onlyhave one open at a time. If the extension is runningin split mode with an active incognito profile, the normal and incognito profiles can eachhave one offscreen document.

Usechrome.offscreen.createDocument() andchrome.offscreen.closeDocument() to create and close an offscreendocument.createDocument() requires the document'surl, a reason, and a justification:

chrome.offscreen.createDocument({url:'off_screen.html',reasons:['CLIPBOARD'],justification:'reason for needing the document',});

Reasons

For a list of valid reasons, see theReasons section. Reasons are set duringdocument creation to determine the document's lifespan. TheAUDIO_PLAYBACK reason sets thedocument to close after 30 seconds without audio playing. All other reasons don't set lifetime limits.

Examples

Maintain the lifecycle of an offscreen document

The following example shows how to ensure that an offscreen document exists. ThesetupOffscreenDocument() function callsruntime.getContexts() to findan existing offscreen document, or creates the document if it doesn't already exist.

letcreating;// A global promise to avoid concurrency issuesasyncfunctionsetupOffscreenDocument(path){// Check all windows controlled by the service worker to see if one// of them is the offscreen document with the given pathconstoffscreenUrl=chrome.runtime.getURL(path);constexistingContexts=awaitchrome.runtime.getContexts({contextTypes:['OFFSCREEN_DOCUMENT'],documentUrls:[offscreenUrl]});if(existingContexts.length >0){return;}// create offscreen documentif(creating){awaitcreating;}else{creating=chrome.offscreen.createDocument({url:path,reasons:['CLIPBOARD'],justification:'reason for needing the document',});awaitcreating;creating=null;}}

Before sending a message to an offscreen document, callsetupOffscreenDocument() to make surethe document exists, as demonstrated in the following example.

chrome.action.onClicked.addListener(async()=>{awaitsetupOffscreenDocument('off_screen.html');// Send message to offscreen documentchrome.runtime.sendMessage({type:'...',target:'offscreen',data:'...'});});

For complete examples, see theoffscreen-clipboard andoffscreen-dom demos on GitHub.

Before Chrome 116: check if an offscreen document is open

runtime.getContexts() was added in Chrome 116. In earlier versions ofChrome, useclients.matchAll()to check for an existing offscreen document:

asyncfunctionhasOffscreenDocument(){if('getContexts'inchrome.runtime){constcontexts=awaitchrome.runtime.getContexts({contextTypes:['OFFSCREEN_DOCUMENT'],documentUrls:[OFFSCREEN_DOCUMENT_PATH]});returnBoolean(contexts.length);}else{constmatchedClients=awaitclients.matchAll();returnmatchedClients.some(client=>{returnclient.url.includes(chrome.runtime.id);});}}

Types

CreateParameters

Properties

  • justification

    string

    A developer-provided string that explains, in more detail, the need for the background context. The user agent _may_ use this in display to the user.

  • reasons

    The reason(s) the extension is creating the offscreen document.

  • url

    string

    The (relative) URL to load in the document.

Reason

Enum

"TESTING"
A reason used for testing purposes only.

"AUDIO_PLAYBACK"
Specifies that the offscreen document is responsible for playing audio.

"IFRAME_SCRIPTING"
Specifies that the offscreen document needs to embed and script an iframe in order to modify the iframe's content.

"DOM_SCRAPING"
Specifies that the offscreen document needs to embed an iframe and scrape its DOM to extract information.

"BLOBS"
Specifies that the offscreen document needs to interact with Blob objects (includingURL.createObjectURL()).

"DOM_PARSER"
Specifies that the offscreen document needs to use theDOMParser API.

"USER_MEDIA"
Specifies that the offscreen document needs to interact with media streams from user media (e.g.getUserMedia()).

"DISPLAY_MEDIA"
Specifies that the offscreen document needs to interact with media streams from display media (e.g.getDisplayMedia()).

"WEB_RTC"
Specifies that the offscreen document needs to useWebRTC APIs.

"CLIPBOARD"
Specifies that the offscreen document needs to interact with theClipboard API.

"LOCAL_STORAGE"
Specifies that the offscreen document needs access tolocalStorage.

"WORKERS"
Specifies that the offscreen document needs to spawn workers.

"BATTERY_STATUS"
Specifies that the offscreen document needs to usenavigator.getBattery.

"MATCH_MEDIA"
Specifies that the offscreen document needs to usewindow.matchMedia.

"GEOLOCATION"
Specifies that the offscreen document needs to usenavigator.geolocation.

Methods

closeDocument()

Promise
chrome.offscreen.closeDocument(
  callback?: function,
)

Closes the currently-open offscreen document for the extension.

Parameters

  • callback

    function optional

    Thecallback parameter looks like:

    () => void

Returns

  • Promise<void>

    Promises are supported in Manifest V3 and later, but callbacks are provided for backward compatibility. You cannot use both on the same function call. The promise resolves with the same type that is passed to the callback.

createDocument()

Promise
chrome.offscreen.createDocument(
  parameters: CreateParameters,
  callback?: function,
)

Creates a new offscreen document for the extension.

Parameters

  • The parameters describing the offscreen document to create.

  • callback

    function optional

    Thecallback parameter looks like:

    () => void

Returns

  • Promise<void>

    Promises are supported in Manifest V3 and later, but callbacks are provided for backward compatibility. You cannot use both on the same function call. The promise resolves with the same type that is passed to the callback.

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2024-12-09 UTC.