Search code examples
htmlweb-frontendlit-element

Embedding web component with easy implementation on the client side


Sorry that the question below is not as specific as it might probably be but that’s the problem - I’ve done my research but I lack domain knowledge to decide if my conclusions are correct :)

I want to make a web component that will be easily embeddable on any website (no matter what frontend technology it uses). Idea is that:

  1. I provide someone (let's call him/her a client) with 2 things:
  • a code to paste on frontend (perfectly if this code would just fetch/render externally hosted (by me) script - to not force clients to implement possible changes on their side)
  • api key identifying client
  1. Client pastes code on his frontend and provides api token to queries
  2. Then it should have two way communication with my backend (through web)

Imo this is exactly the case like e.g. embedding google map: (https://developers.google.com/maps/documentation/embed/map-generator#create-project)

 <iframe width="600" height="450" style="border:0" loading="lazy" allowfullscreen
src="https://www.google.com/maps/embed/v1/undefined?origin=...&q=...&destination=...&center=...&zoom=...&key=...">

As far as I understand they just create iframe and fetch .js from their server. Now, I would like to know if doing it that way is my best option. I’m looking for a framework to make development as fast as possible. I’ve found lit-elements (https://lit.dev/) - do you think it might be a good choice?


Solution

  • Yes that is absolutely possible. Load your js as a module.

    <script type="module" src="path-to-your-module.mjs"></script>
    

    Then you can achieve the following (all inlined for presentability here):

    <script type="module">
    import {
      LitElement,
      html,
      css
    } from "https://unpkg.com/lit-element/lit-element.js?module";
    
    class ElementWithAPIKey extends LitElement {
    
     static get properties() {
      return {
        apiKey: {type: String}
      };
     }
    
     render() {
      return html`
          <h1>Example APIKEY: ${this.apiKey}</h1>
      `;
     }
    }
    
    customElements.define("my-element", ElementWithAPIKey);
    </script>
    <my-element apiKey="CAFEBABE"></my-element>

    This would work, no matter which framework you use.