9

I'm trying to figure out the best way to create a javascript widget that: - Can be embedded in most websites - It's self contained (initially only - Can be configured

An example of desired functionality would be Stripe's checkout widget: link

I'm not getting very lucky in finding resources, tutorial or best practices. From what I've seen so far the most common flow is:

  1. Initial self executed script is inserted in website
  2. The script reads the passed configuration and merges it with the default
  3. Html element that triggers the behaviour (e.g. button), and bound to a handler
  4. An iFrame is created passing the configuration and most of the logic happens

My current doubts are:

  1. Is there a recommended Webpack (or similar) template to create the initial script from ES6 project?
  2. Communication (both ways) between website and iframe
  3. Security concerns

Any input is welcome!

jasalguero
  • 4,142
  • 2
  • 31
  • 52
  • For communicating between site and iframe you can probably use something like postMessage. https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage – CF256 Aug 22 '17 at 15:12
  • Open up an open source third party library and see how they do it. I think the scope of your question is too large and broad to answer here on SO. There are so many ways to actually do what you want. Also, I would suggest adding the code of something you have already tried. – hitautodestruct Mar 12 '23 at 13:49

1 Answers1

-1

I struggled with this myself and ended up building www.simplicityblocks.com to solve some of the challenges with this. I did end up using an iFrame as the method of isolation for the widget. This is wrapped inside of a custom web component (<simplicity-block>). I also provide a bunch of configuration options that get configured on a loaded from the server-side. It is my opinion that this is the best method for creating an embeddable widget that needs to be generically installable in any web page. Regarding the communication between the widget and the host page, I implemented multiple ways to do this. The first is using user-defined attributes which are set inside the custom component. When the widget is loaded into the iframe, these attributes and their values are passed as URL parameters to the widget. If the page host changes any of the attributes programmatically, the widget is re-loaded with the new parameter value. I also provide a sendMessage method that can pass any object along to the widget without reloading. The widget only needs to have a message listener in it. These various communication methods are described in further detail at https://www.simplicityblocks.com/documentation/VanillaTestPage.html

Mifo
  • 563
  • 6
  • 6