主要内容

本页采用了机器翻译。点击此处可查看英文原文。

在自定义 Web App 和嵌入式 MATLAB Web App 之间交换数据

您可以使用以下工作流促进自定义 Web App 和 MATLAB®Web App 之间的数据交换。首先,配置服务器以进行跨域交互。接下来,使用 iframe 标记将 MATLABWeb App 嵌入到 Web 中。然后,Web 使用 MATLAB 将数据发送到 JavaScript® App。在 MATLAB App 内部,特定的 uihtml 元素和回调函数处理这些数据消息。最后一步是将 MATLABWeb App 部署并嵌入到 Web 中,从而实现两者之间的动态交互。此功能要求浏览器启用 cookie。

小心

在网页的 HTML iframe 元素中嵌入 MATLABWeb App 可能会带来许多安全风险。这些风险包括但不限于点击劫持、跨站点脚本 (XSS) 和跨站点请求伪造 (CSRF)。需要考虑的另一个因素是,此过程需要浏览器启用 cookie,从而引入额外的漏洞。这些风险共同使系统面临更广泛的攻击面。因此,确保用于嵌入的 MATLAB Web App 安全且可信至关重要。此外,嵌入只应在经过证明的安全且值得信赖的网站上才被允许。这可以通过在服务器上正确设置 allowed_frame_ancestors 选项来实现,从而提供额外的保护层。

配置 MATLAB Web App Server 以允许数据交换

配置 MATLAB Web App Server™ 以使用 allowed_frame_ancestorsallowed_event_origins 选项允许自定义 Web 的域。

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

创建自定义 Web 并设置通信

  • 使用 HTML 开发自定义 Web,并使用 iframe 标记将 MATLAB Web App 嵌入页面中。如果您没有准备好嵌入的 MATLABWeb App,您可以在打包并将 Web App 部署到 MATLAB Web App Server 后返回此步骤。例如:

    <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>

  • 在自定义 Web 上实现 JavaScript 函数,以在 iframe HTML 元素内向 MATLABWeb App 发布消息。例如:

    // 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;
       }
    });
    

开发 MATLAB App

数据已发送至 MATLAB

  • 开发一个具有两个 uihtml (MATLAB) 组件的 MATLAB App。为了给这些组件提供内容,请为每个组件创建专用的 HTML 文件,并使用 HTMLSource (MATLAB) 属性进行链接。例如:

    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';

  • HTMLEventReceivedFcn (MATLAB)DataChangedFcn (MATLAB) 回调合并到将数据发送到 MATLAB App 的 uihtml 组件中。这些回调从自定义 Web 接收数据。例如:

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

MATLAB 发送的数据

在用于管理从 MATLAB App 发送到自定义 Web App 的数据的第二个 uihtml 组件上使用 sendEventToHTMLSource (MATLAB) 函数,将携带相关数据的特定事件发送到 HTML 界面。例如:

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

处理从自定义 Web App 发送到 MATLAB App 的数据

  • 制作一个 JavaScript 函数、setup(htmlComponent),用于监听 "message" 事件并将数据从自定义 Web 发送到 MATLAB。例如:

    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. 
            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.");
            }
        });
    }
    

  • 将此 JavaScript 函数嵌入 HTML 文件中。

MATLAB 中处理数据

  • 在 MATLABWeb App 中,获取通过 HTMLEventReceivedFcn 回调中的 JavaScript sendEventToMATLAB 方法发送的事件数据。例如:

    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

    此外,您还可以使用 DataChangedFcn (MATLAB) 回调来获取事件数据。

  • 在 MATLAB 环境中根据需要使用接收到的数据。

处理从 MATLAB App 发送到自定义 Web App 的数据

在您的 JavaScript 代码中,创建一个 setup(htmlComponent) 函数。在此函数内部,附加一个事件监听器,用于监听从 sendEventToHTMLSource (MATLAB) MATLAB 函数发送的事件。当事件触发时,使用监听器从事件中提取数据。使用 postMessage 方法将此数据发送到自定义 Web。确保此 JavaScript 嵌入在 HTML 文件中,该文件应该可以从您的 MATLAB App 访问。例如:

// 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);
    });
}

打包并部署 MATLAB App

  • 使用 compiler.build.webAppArchive (MATLAB Compiler) 函数打包 MATLAB App。将 HTML 和 JavaScript 文件作为依赖项包含在内。例如:

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

  • 将 Web App 存档部署到 MATLAB Web App Server,然后使用 iframe 标记将其合并到您的自定义 Web 中。要保护 Web App 的 URL,请导航到 Web App 主页,右键点击所需的 Web App,然后从上下文菜单中选择 Copy link。使用此 URL 将 Web App 嵌入到自定义 Web 的 iframe 标记中。有关详细信息,请参阅创建自定义 Web 并设置通信

另请参阅

| (MATLAB) | (MATLAB Compiler)

主题