Loading Posts...

Using Angular-Elements in a Chrome Extension

Using Angular-Elements in a Chrome Extension
Photo by Greyson Joralemon on Unsplash

Say Hi! to Angular-Elements

Despite the fact that Angular-Elements is not yet widely used, they are a powerful tool for writing independent and autonomous components that can be leveraged at any website by adding literally a couple lines of the code.

If you aren’t familiar with Angular-Elements I’d strongly recommend to read about it. In short, Angular-Elements is an Angular application that leverages Web Components standard to provide ability for defining Angular application as an html tag. What differentiate Angular-Elements from an Angular application is the way for bootstrapping::

Angular is responsible for creating the shell of the application, which is subsequently used when registering a custom element in the browser. The customElements.define() function registers an Angular application with the specified custom-element. All you need to do is to add a to the page markup, and Angular application will be rendered inside this tag.

customElements.define() is part of the ECMAScript standard and is supported by all major browsers.

This approach opens up new horizons for using Angular applications. I’d like to share how to use Angular-Elements with Chrome Extensions; often the essence of the such extensions is to extend page view by adding html tags to it. With Angular-Elements adding and processing elements on the page becomes pretty straightforward.

Specificity of Chrome Extension

Although there is nothing special about using Angular-Elements in the Chrome Extension, it is important to understand how the scripts are loaded onto the page. Let’s consider following diagram:

Page and Extension contexts

As it shown an extension code can be executed in two different contexts:

  • page context: there is access to window object and DOM elements, while there is no access to the Chrome API;
  • extension context: has independent window object which has nothing in common with the window object from the running page. It doesn’t have access to the page javascript, but it is allowed to manipulate the DOM and call the Chrome API.

So, how to load scripts in each of the contexts?

For executing script in the page context, the one must be loaded in the following way:

By adding a

Loading Posts...