Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Chrome extensions, why use a background page with HTML?

I understand that the background page of a Chrome extension is never displayed. It makes sense to me that a background page should contain only scripts. In what situations would HTML markup ever be needed?

At https://developer.chrome.com/extensions/background_pages there is an example with an HTML background page, but I haven't been able to get it to work (perhaps because I am not sure what it should be doing).

Are there any examples of simple Chrome extensions which demonstrate how HTML markup can be useful in a background page?

like image 216
James Newton Avatar asked Jan 05 '23 18:01

James Newton


1 Answers

Historical reasons

The background page is, technically, a whole separate document - except it's not rendered in an actual tab.

For simplicity's sake, perhaps, extensions started with requiring a full HTML page for the background page through the background_page manifest property. That was the only form.

But, as evidenced by your question, most of the time it's not clear what the page can actually be used for except for holding scripts. That made the entire thing being just a piece of boilerplate.

That's why when Chrome introduced "manifest_version": 2 in 2012 as a big facelift to extensions, they added an alternative format, background.scripts array. This will offload the boilerplate to Chrome, which will then create a background page document for you, succinctly called _generated_background_page.html.

Today, this is a preferred method, though background.page is still available.

Practical reasons

With all the above said, you still sometimes want to have actual elements in your background page's document.

  • <script> for dynamically adding scripts to the background page (as long as they conform to extension CSP).
    Among other things, since you can't include external scripts through background.scripts array, you need to create a <script> element for those you whitelist for the purpose.
  • <canvas> for preparing image data for use elsewhere, for example in Browser Action icons.
  • <audio> for producing sounds.
  • <textarea> for (old-school) working with clipboard (don't actually do this).
  • <iframe> for embedding an external page into the background page, which can sometimes help extracting dynamic data.
  • ..possibly more.

It's debatable which boilerplate is "better": creating the elements in advance as a document, or using document.createElement and its friends as needed.

In any case, a background page is always a page, whether provided by you or autogenerated by Chrome. You can use all the DOM functions you want.

like image 53
Xan Avatar answered Feb 15 '23 06:02

Xan