Search code examples
javascripthtmlreactjscdn

How can we create our own React.js components as CDN links?


I have a Chatbot component in my Next.js app and I want anyone to use to as a chatbot in their website using <script tag. Suppose I put component in my public folder to have public access.

How can I implement this kind of functionality so that anyone can add this link in the script tag of their application and have access to my Chatbot

<script type="module" src="https://my-app-url/Chatbot.js" defer></script>

enter image description here


Solution

  • The simplest way would be to use an iframe.

    You can host your Next.js app with a page that only contains the chatbot component and set the background color as transparent.

    background-color : transparent;
    

    Then, anyone with access to your app can use an iframe to embed the chatbot in their own website. Adding allowtransparency="true" will achieve your desired effect.

    <iframe src="https://your-nextjs-app/chatbot-page" allowtransparency="true"></iframe> 
    

    more info on iframe allowtransparency.


    To create the iframe with javascript:

    // Create the iframe element
    var iframe = document.createElement('iframe');
    
    // Set the iframe attributes
    iframe.src = 'https://your-nextjs-app/chatbot-page';
    iframe.style.position = 'fixed';
    iframe.style.bottom = '0';
    iframe.style.right = '0';
    iframe.style.width = '400px';
    iframe.style.height = '600px';
    iframe.style.border = 'none';
    iframe.style.opacity = '0.5';
    iframe.style.zIndex = '9999';
    iframe.allowtransparency = true;
    iframe.style.backgroundColor = 'transparent';
    
    // Append the iframe to the document body
    document.body.appendChild(iframe);