Skip to content

Proposal: chrome.offscreen.executeScript API for easier DOM access in service worker #881

@Juraj-Masiar

Description

@Juraj-Masiar

Motivation

Current implementation of the offscreen API is complicated and requires many steps, often only to perform a simple DOM operation.

Solution

Browser handled offscreen document:

  • created by browser when needed
  • destroyed after usage or together with the service worker (if func is async and won't resolve in time)

Example

Let's say we want to implement a function that fetches a page title:

async function fetchPageTitle(url: string) {
  const pageHtml = await (await fetch(url)).text();
  const pageTitle = await chrome.offscreen.executeScript({
    args: [pageHtml],
    func: (pageHtml) => {
      const parser = new DOMParser();
      const doc = parser.parseFromString(pageHtml, 'text/html');
      return doc.title;    // returning a Promise should be also supported!
    },
  });
  return pageTitle;
}

Why is this better

  1. it's a familiar API (see scripting.executeScript)
  2. the code execution flow is straightforward - easy to reason about
  3. the code logic is nicely encapsulated inside a single function (not across files/message handlers)
  4. potentially better cross browser compatibility - one could easily write a polyfill for Firefox event page that simply executes the provided function in the current event page

What's missing / not clear

I'm not sure about the "reasons" parameter, do we need that?

See also

Chromium issue for this proposal.

Metadata

Metadata

Assignees

No one assigned

    Labels

    needs-triage: chromeChrome needs to assess this issue for the first time

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions