Embed chat using iframe - createIT
Get a free advice now!

    Pick the topic
    Developer OutsourcingWeb developingApp developingDigital MarketingeCommerce systemseEntertainment systems

    Thank you for your message. It has been sent.
    Tags

    Embed chat using iframe

    Embed chat using iframe

    It is often a good solution to use iframe when creating different applications that will be embedded on third-party websites. Iframe provides a separation between styles and code of both websites. This resolves typical problems like: javascript conflicts or global style overwrites.

    How embed code should look like? The first approach will be to just paste the raw HTML code of iframe. However, pasting iframe is often forbidden for security reasons, or CMS makes it possible to paste only some code into the HEAD of the page. Using the javascript embed, we can easily add custom logic to the loading mechanism, add lazy-loading or change the iframe source url.

    Chat widget

    We will use SendBird demos for presentation, this chat in particular: https://sendbird.github.io/uikit-js-marketing/iframe.html?id=example-app–primary&viewMode=story . The chat uses an external url and is fully functional. Our goal will be to embed it as iframe on any website.

    chat with contacts

    How to embed iframe

    We have 3 elements here:

    1. /embed/widget.js – for appending iframe to DOM
    2. iframe source – chat application
    3. embed code for loading /embed/widget.js (added in the HEAD section of target website)

    Those elements are working cross-domain. You can host: widget.js and iframe source on different domains.

    Embed widget

    This file creates an iframe tag with src and appends it into the DOM of the parent page. We’re hosting it on our server. Inline styles add a fixed position and remove default browser styles. Parent div gets width and height from the global window variable window.mychat.

    // /embed/widget.js
    /**
     * Widget Embed iframe code
     * (also external domain)
     *
     */
    (function(){
        window.mychat = window.mychat || {};
        var iframe2 = document.createElement('div');
        iframe2.id = "iframe2";
        var styles = {
            "border": "0px",
            "background-color": "transparent",
            "pointer-events": "none",
            "z-index": "2147483639",
            "position": "fixed",
            "bottom": "0px",
            "width": window.mychat.iframeWidth,
            "height": window.mychat.iframeHeight,
            "overflow": "hidden",
            "opacity": "1",
            "max-width": "100%",
            "right": "0px",
            "max-height": "100%"
        };
        Object.assign(iframe2.style, styles);
        var iframe1 = document.createElement('iframe');
        // chat source (external url)
        iframe1.src = 'https://sendbird.github.io/uikit-js-marketing/iframe.html?id=example-app--primary&viewMode=story';
        iframe1.id = "iframe1";
        iframe1.allow = "autoplay; camera; microphone";
        var styles = {
            "pointer-events": "all",
            "background": "none",
            "border": "0px",
            "float": "none",
            "position": "absolute",
            "inset": "0px",
            "width": "100%",
            "height": "100%",
            "margin": "0px",
            "padding": "0px",
            "min-height": "0px"
        };
        Object.assign(iframe1.style, styles);
        iframe2.appendChild(iframe1);
        document.querySelector('body').appendChild(iframe2);
        
    })();
    

    Iframe source

    The iframe source can be anything: chat, application, form, or some other website. The only requirement is that the target website can’t have ‘X-Frame-Options’ set to ‘sameorigin’ nor ‘deny’. For example, we will be able to render https://wiktionary.org in our iframe:

    // /embed/widget.js
    // chat source (external url)
    iframe1.src = 'https://wiktionary.org';
    iframe1.id = "iframe1";
    
    wiktionary screenshot

    Embed code

    The final code that needs to be pasted into the HEAD section of the target page is simple javascript that appends an /embed/widget.js file from our domain. In addition, the Client can customize iframe size by changing the iframeWidth and iframeHeight variables.

    Similar code is used by Google Analytics to add tracking scripts. It’s quite a common solution for every embeddable element across the internet.

    It’s worth to mention that /embed/widget.js includes our widget logic, and the file is hosted on our server. So, if there are any updates to the code, we can add changes directly to the widget.js file (the embed code on target page doesn’t need to be updated ).

    <!-- TARGET PAGE -->
    <html>
    <head>
        <style>
            body {
                background:#fafafa;
                border:12px solid blueviolet;
                padding:20px;
            }
        </style>
        <!--Embed Code starts-->
        <script type="text/javascript">
            window.mychat = window.mychat || {};
            // domain for widget code embed
            window.mychat.server = 'https://localhost:3002';
            window.mychat.iframeWidth = '700px';
            window.mychat.iframeHeight = '700px';
            (function() {
                var mychat = document.createElement('script'); mychat.type = 'text/javascript'; mychat.async = true;
                mychat.src = window.mychat.server + '/embed/widget.js';
                var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(mychat, s);
            })();
        </script>
        <!--Embed Code ends-->
    </head>
    <body>
    <h2>This is my website</h2>
    <div style="min-height:500px; background:#ccc; display:flex; padding:20px;">Something here</div>
    </body>
    </html>
    
    working chat gif animation

    That’s it for today’s tutorial. Make sure to follow us for other useful tips and guidelines, and don’t forget to sign up for our newsletter.

    Do you need someone to implement this solution for you? Check out our custom web application development page or specialists for hire in the outsourcing section. Are you considering a global project and are uncertain how to proceed?

    Comments
    3 response
    1. Hi, great article! I have a question though – ” if there are any updates to the code, we can add changes directly to the widget.js file (the embed code on target page doesn’t need to be updated ” – what if the widget.js gets cached? Without proper cache busting technique I have a feeling that this may fail, and cache busting forces to apply change to the client that uses the widget.js whenever a new version gets released.

      • Hello!
        You’re absolutely right in pointing out the potential issue with caching. Since you want to avoid forcing clients to update the embed code, you can dynamically append the versioning information on the client side.

        
        (function() {
            // Use the current timestamp to ensure uniqueness
            var timestamp = new Date().getTime();
            var widgetScript = document.createElement('script'); 
            widgetScript.src = 'https://yourserver.com/embed/widget.js?_=' + timestamp;
            document.body.appendChild(widgetScript);
        })();
        

        If your widget.js is generated as PHP script – you can use other solution: Use Cache-Control headers to prevent caching or to specify caching behavior.

        
        header("Content-Type: application/javascript");
        header("Cache-Control: no-cache, must-revalidate");
        header("Pragma: no-cache"); // HTTP 1.0.
        header("Expires: 0"); // Proxies.
        echo "// Your dynamic JavaScript content here";
        
    2. Hi
      I’ve tried to use Iframe in my blazor WASM application to integrate Element chat. But I’m getting the following error “Refused to display ‘https://app.element.io/’ in a frame because it set ‘X-Frame-Options’ to ‘sameorigin’.”

    Add comment

    Your email address will not be published. Required fields are marked *

    Popular news

    Automating stock and price updates in WooCommerce
    • Dev Tips and Tricks

    Automating stock and price updates in WooCommerce

    September 23, 2024 by createIT
    Integrating advanced subscription features in WooCommerce
    • Dev Tips and Tricks

    Integrating advanced subscription features in WooCommerce

    September 16, 2024 by createIT
    Fetching Time records from ActiveCollab API
    • Dev Tips and Tricks

    Fetching Time records from ActiveCollab API

    September 9, 2024 by createIT
    Docker Compose for PrestaShop
    • Dev Tips and Tricks

    Docker Compose for PrestaShop

    September 2, 2024 by createIT
    WordPress wizard in admin – step by step
    • Dev Tips and Tricks

    WordPress wizard in admin – step by step

    August 29, 2024 by createIT
    Order Status Sync between PrestaShop and External APIs
    • Dev Tips and Tricks

    Order Status Sync between PrestaShop and External APIs

    August 26, 2024 by createIT
    What is PHP used for in web development 
    • Dev Tips and Tricks

    What is PHP used for in web development 

    August 22, 2024 by createIT
    Automating WooCommerce product availability date
    • Dev Tips and Tricks

    Automating WooCommerce product availability date

    August 15, 2024 by createIT
    WP Quiz Adventure – FAQ
    • Dev Tips and Tricks

    WP Quiz Adventure – FAQ

    August 12, 2024 by createIT

    Support – Tips and Tricks
    All tips in one place, and the database keeps growing. Stay up to date and optimize your work!

    Contact us