Main Content

Exchange Data Between Custom Web Page and Embedded MATLAB Web App

You can facilitate data exchange between a custom web page and a MATLAB® web app using the following workflow. First, configure the server for cross-origin interactions. Next, embed the MATLAB web app into the web page using an iframe tag. The web page then dispatches data to the MATLAB app using JavaScript®. Inside the MATLAB app, specific uihtml elements and callback functions handle these data messages. The final step involves deploying and embedding the MATLAB web app into a web page, thereby enabling dynamic interactions between the two. This functionality requires that a browser has cookies enabled.

Caution

Embedding a MATLAB web app within an HTML iframe element on a webpage can potentially introduce numerous security risks. These risks include, but are not limited to, clickjacking, Cross-Site Scripting (XSS), and Cross-Site Request Forgery (CSRF). Another factor to consider is that this process requires a browser to enable cookies, introducing an additional vulnerability. These risks collectively expose the system to a broader attack surface. Therefore, it's crucial to ascertain that the MATLAB web app intended for embedding is both secure and trustworthy. Furthermore, the embedding should only be permitted on websites that are proven to be secure and trustworthy. This can be achieved by properly setting the allowed_frame_ancestors option on the server, thus providing an additional layer of protection.

Configure MATLAB Web App Server to Permit Data Exchange

Configure MATLAB Web App Server™ to allow the domain of the custom web page using the allowed_frame_ancestors and allowed_event_origins options.

webapps-config set allowed_frame_ancestors "https://www.example.com"
webapps-config set allowed_event_origins "https://www.example.com:8001"

Create Custom Web Page and Setup Communication

  • Develop a custom web page using HTML and embed the MATLAB web app within the page using an iframe tag. If you do not have a MATLAB web app ready to embed you can return to this step once you've packaged and deployed a web app to MATLAB Web App Server. For example:

    <iframe id="mainFrame" name="mainFrame" class="mainContainer"
            src="https://<hostname>:<port>/webapps/home/session.html?app={webAppName}"
            style="height:600px;width:600px" title="webpage"></iframe>

  • Implement a JavaScript function on the custom web page to post a message to the MATLAB web app within the iframe HTML element. For example:

    // In this example, we are assuming that data is being sent on clicking a button.
    // And data that is returned from a MATLAB app is displayed as a text element.
    
    // Define a function to send data to the iframe
    var buttonOne = document.getElementById("buttonOne");
    function dataExchangeWithIframe(event) {
        // Access the iframe using its ID
        const frame = document.getElementById('mainFrame');
        
        // Define the data you want to send
        const data = [10];
        
        // Define the origin of the target iframe where the message will be posted (MATLAB Web App Server URL)
        const targetOrigin = "https://<hostname>:<port>";
        
        // Use postMessage method to send the data to the target iframe
        frame.contentWindow.postMessage(data, targetOrigin);
    }
    buttonOne.addEventListener('click', dataExchangeWithIframe, false);
    
    // Add an event listener to listen for the event from the MATLAB web app
    window.addEventListener("message", function (event) {                       
       // CRITICAL: Check origin to verify you are receiving data from a trusted origin. 
       // Validate that the event came from your MATLAB Web App Server and ignore any other requests.
       if (event.origin.startsWith('https://<hostname>:<port>')) {            
            var receivedData = event.data;
            console.log("Data Received from MATLAB app: ", receivedData);
            document.getElementById('dataFromMatlab').textContent = "Data from MATLAB: " + receivedData;
       }
    });
    

Develop MATLAB App

Data Sent to MATLAB App

  • Develop a MATLAB app featuring two uihtml (MATLAB) components. To provide content for these components, create a dedicated HTML file for each component and link it using the HTMLSource (MATLAB) property. For example:

    app.DataToMatlab = uihtml(app.UIFigure);    % used for managing data sent to MATLAB app from custom web page
    app.DataToMatlab.HTMLSource = 'dataToMatlab.html'; 
    app.DataFromMatlab = uihtml(app.UIFigure);  % used for managing data sent from MATLAB app to custom web page 
    app.DataFromMatlab.HTMLSource = 'dataFromMatlab.html';

  • Incorporate either HTMLEventReceivedFcn (MATLAB) or DataChangedFcn (MATLAB) callbacks into the uihtml component where data is being sent to MATLAB app. These callbacks receive data from the custom web page. For example:

    app.DataToMatlab.HTMLEventReceivedFcn = createCallbackFcn(app, @handleDataToMatlab, true); % use this OR
    app.DataToMatlab.DataChangedFcn = createCallbackFcn(app, @handleDataToMatlab, true);
    

Data Sent from MATLAB App

Use the sendEventToHTMLSource (MATLAB) function on the second uihtml component used for managing data sent to custom web page from MATLAB app, send specific events carrying associated data to the HTML interface. For example:

% Send 'dataFromMatlab' event with 'rmsVal' to associated HTML document in UIHTML component.
app.DataFromMatlab.sendEventToHTMLSource('dataFromMatlab', rmsVal);

Handle Data Sent to MATLAB App from Custom Web Page

  • Craft a JavaScript function, setup(htmlComponent), that listens for "message" events and sends data from the custom web page to MATLAB. For example:

    console.log("Receive script loaded.");
    // Define a setup function that takes an HTML component as an argument
    function setup(htmlComponent) {
        // Add an event listener to the window object for "message" events
        window.addEventListener("message", function (event) {
            // CRITICAL: Check origin to verify you are receiving data from a trusted origin. 
            // Validate that the event came from your MATLAB Web App Server and ignore any other requests.
            if (event.origin.startsWith('https://<hostname>:<port>')) {
                // Log the event origin to the console
                console.log("Event origin: ", event.origin);
                // Extract the data from the event
                var datatomatlab = event.data;
                
                // Send the received data to the MATLAB app through the "dataToMatlab" event
                htmlComponent.sendEventToMATLAB("dataToMatlab", datatomatlab);
                console.log("Send received data to MATLAB: ", datatomatlab);
            } else {
                // If the origin of the event is not the expected origin, log "Wrong origin." to the console
                console.error("Wrong origin.");
            }
        });
    }
    

  • Embed this JavaScript function within the HTML file.

Process Data in MATLAB

  • Within the MATLAB web app, fetch the event data sent via the JavaScript sendEventToMATLAB method in the HTMLEventReceivedFcn callback. For example:

    function handleDataToMatlab(app, event)
        % Extract the name and data of the HTML event from the event object
        eventName = event.HTMLEventName;
        % Check if the event name matches 'dataToMatlab'
        if strcmp(eventName, 'dataToMatlab')
            % If it matches, extract the passed data from the event
            receivedData = event.HTMLEventData;
            % Now, you can use the 'receivedData' variable within your MATLAB code.
            % Further processing or visualization code can go here
        end
    end

    In addition, you can use a DataChangedFcn (MATLAB) callback to get the event data as well.

  • Use the received data as required within the MATLAB environment.

Handle Data Sent to Custom Web Page from MATLAB App

In your JavaScript code, create a setup(htmlComponent) function. Inside this function, attach an event listener for an event sent from the sendEventToHTMLSource (MATLAB) MATLAB function. When the event is triggered, use the listener to extract the data from the event. Use a postMessage method to send this data to the custom web page. Ensure that this JavaScript is embedded in an HTML file, which should be accessible from your MATLAB application. For example:

// Define a setup function that takes an HTML component as an argument
console.log("Receive script loaded.");
function setup(htmlComponent) {
    console.log("setup function called.");
    htmlComponent.addEventListener("dataFromMatlab", function (event) {
        dataFromMatlab = event.Data;        
        // Define targetOrigin to point to the custom web page where the data will be sent
        const targetOrigin = "https://<custom_web_page_hostname>:<port>";
        // Use window.top to send the data to the target webpage
        window.top.postMessage(dataFromMatlab, targetOrigin);
        console.log("Received data from Matlab: ", dataFromMatlab);
    });
}

Package and Deploy MATLAB App

  • Package the MATLAB app using the compiler.build.webAppArchive (MATLAB Compiler) function. Include the HTML and JavaScript files as dependencies. For example:

    files = ["dataToMatlab.html", "dataToMatlab.js", "dataFromMatlab.html", "dataFromMatlab.js"]
    results = compiler.build.webAppArchive("myWebApp.mlapp",...
        AdditionalFiles=files,...
        OutputDir="output",...
        Verbose="on")

  • Deploy the web app archive to MATLAB Web App Server, then incorporate it into your custom web page using an iframe tag. To secure the URL of the web app, navigate to the web apps home page, right-click the desired web app, and select Copy link from the context menu. Use this URL to embed the web app within your custom web page's iframe tag. For details, see Create Custom Web Page and Setup Communication.

See Also

| (MATLAB) | (MATLAB Compiler)

Related Topics