Main Content

uihtml

Create HTML UI component

Description

h = uihtml creates an HTML UI component in a new figure and returns the HTML UI component object. MATLAB® calls the uifigure function to create the figure.

With the uihtml function, you can embed HTML, JavaScript®, or CSS content in your app and interface with third-party libraries to display content like widgets or data visualizations. All supporting files (including HTML, JavaScript, CSS, images) must be saved in a location that your local file system can access.

example

h = uihtml(parent) creates an HTML UI component in the specified parent container. The parent can be a Figure object created with the uifigure function, or one of its child containers.

example

h = uihtml(___,Name,Value) specifies HTML UI component properties using one or more name-value pair arguments. For example, 'HTMLSource','timepicker.html' sets the HTML source to the specified HTML file.

Examples

collapse all

Create an HTML component and display formatted text in it using HTML markup.

fig = uifigure('Position',[561 497 333 239]);
h = uihtml(fig);
h.HTMLSource = '<p style="font-family:arial;"><b><span style="color:red;">Hello</span> <u>World</u>!</b></p>';

Create an HTML file to embed audio and video elements in your app and reference media source files.

First, create an empty HTML UI component in a figure.

fig = uifigure;
fig.Position = [500 500 380 445];

h = uihtml(fig);
h.Position = [10 10 360 420];

Then, create an HTML file called audio_videoplayers.html. In the file, add audio and video elements and specify their file sources relative to the path of the HTML file. In this example, the media files are in the same directory as the HTML file.

<!DOCTYPE html>
<html>
	<body style="background-color:white;font-family:arial;">
		<p style="padding-left:20px">
		Play audio file:
		</p>
		
		<audio controls style="padding-left:20px">
			<source src="./handel_audio.wav" type="audio/wav">
			<source src="./handel_audio.oga" type="audio/ogg">
			Your browser does not support the audio tag.
		</audio>
		
		<p style="padding-left:20px">
		Play video file:
		</p>
		
		<video width="320" height="240" controls style="padding-left:20px">
			<source src="./xylophone_video.mp4" type="video/mp4">
			<source src="./xylophone_video.oga" type="video/ogg">
			Your browser does not support the video tag.
		</video>
		
	</body>
</html>

Now, embed the HTML file in your app by setting the HTMLSource property to the full path to the file.

h.HTMLSource = fullfile(pwd,'audio_videoplayers.html');

Create an htmlComponent JavaScript® object that displays the data that is set on an HTML UI component in MATLAB®.

First, create an empty HTML UI component and position it within a figure.

fig = uifigure;
fig.Position = [500 500 490 180];

h = uihtml(fig);
h.Position = [20 20 450 130];

Then, create an HTML file called displayDataFromMATLAB.html. In the file,

  • Use a style tag to define internal CSS styles for the <div> elements that display text.

  • Write a setup function inside of a <script> tag to connect your JavaScript object, called htmlComponent, to the HTML UI component you created in MATLAB.

  • Add an event listener within the setup function. The event listener listens for "DataChanged" events on the htmlComponent JavaScript object and creates a listener callback function. When a "DataChanged" event occurs, the listener callback function updates the "dataDisplay" <div> element with the value that is set to the Data property in MATLAB.

<!DOCTYPE html>
<html>
<head>
<style>
#prompt {
  font-family: sans-serif;
  text-align:center;
  border-radius: 5px;
  background-color: lightblue;
  padding: 20px;
}

#dataDisplay {
  border-radius: 5px;
  height: 10vh;
  padding: 12px 20px;
}
</style>

<script type="text/javascript">
         
        function setup(htmlComponent) {
		          
            htmlComponent.addEventListener("DataChanged", function(event) {
            document.getElementById("dataDisplay").innerHTML = htmlComponent.Data;
            });     
        }
</script>
</head>

<body>
     <div id="prompt">
		
	<span><label for="prompt"><strong>Data from MATLAB will display here:</strong></label></span>
	<br/><br/>
	<div id ="dataDisplay">
	Please set data in MATLAB...
	</div>
		
     </div>
</body>

</html>

Now, in MATLAB, set the value of the HTMLSource property to the path to the HTML file.

h.HTMLSource = fullfile(pwd,'displayDataFromMATLAB.html');

Set the value of the Data property for the HTML UI component. Notice how the htmlComponent JavaScript object updates in your HTML UI component.

h.Data = "Hello World!";

Create an htmlComponent JavaScript® object that generates a random number when a button is clicked, and display the number in MATLAB®.

First, create an empty HTML UI component and position it within a figure.

fig = uifigure;
fig.Position = [500 500 490 180];

h = uihtml(fig);
h.Position = [20 20 450 130];

Then, create an HTML file called generateJSRandomNumber.html. In the file,

  • Use a style tag to define internal CSS styles for a button element.

  • Write a setup function inside of a <script> tag to connect your JavaScript object, called htmlComponent, to the HTML UI component you created in MATLAB.

  • Add an event listener within the setup function. The event listener listens for "click" events on the button and creates a listener callback function. When a click event occurs, the listener callback function sets the Data property of the htmlComponent JavaScript object to a randomly generated integer between 1 and 100.

<!DOCTYPE html>
<html>
<head>
<style>
button {
  width: 100%;
  font-family: sans-serif;
  background-color: #4CAF50;
  color: white;
  font-size: 1rem;
  text-shadow: 1px 1px 1px #000;
  padding: 5px 20px;
  margin: 8px 0;
  border: none;
  border-radius: 10px;
  line-height: 2.5;
  cursor: pointer;
  background-image: linear-gradient(to top left,
                                      rgba(0, 0, 0, .2),
                                      rgba(0, 0, 0, .2) 30%,
                                      rgba(0, 0, 0, 0));
  box-shadow: inset 2px 2px 3px rgba(255, 255, 255, .6),
             inset -2px -2px 3px rgba(0, 0, 0, .6);
}

button:hover {
  background-color: #45a049;
}

button:focus {
outline: 0;
}

button:active {
    box-shadow: inset -2px -2px 3px rgba(255, 255, 255, .6),
                inset 2px 2px 3px rgba(0, 0, 0, .6);
}
</style>

   <script type="text/javascript">
         
      function setup(htmlComponent) {
                      
         document.getElementById("generateRandomNumber").addEventListener("click", function(event) {
            htmlComponent.Data = Math.floor(Math.random() * 100) + 1;
         });
      }
   </script>
</head>

   <body>
     <button id="generateRandomNumber">Generate Random Number</button><br/> 
   </body>
	
</html>

Now, in MATLAB, set the value of the HTMLSource property to the path to the HTML file. Create a DataChangedFcn callback function that displays the random number your JavaScript code generates. Click the Generate Random Number button to see the value of the Data property display in the MATLAB Command Window.

h.HTMLSource = fullfile(pwd,'generateJSRandomNumber.html');
h.DataChangedFcn = @(src,event)disp(h.Data);

Input Arguments

collapse all

Parent container, specified as a Figure object created using the uifigure function, or one of its child containers: Tab, Panel, ButtonGroup, or GridLayout. If you do not specify a parent container, MATLAB calls the uifigure function to create a new Figure object that serves as the parent container.

Name-Value Pair Arguments

Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and Value is the corresponding value. Name must appear inside quotes. You can specify several name and value pair arguments in any order as Name1,Value1,...,NameN,ValueN.

Example: h = uihtml(uifigure,'HTMLSource','C:\Work\expenses.html');

Note

The properties listed here are only a subset. For a complete list, see HTML Properties.

HTML markup or file, specified as a character vector or string scalar that contains either HTML markup or the path to an HTML file. All HTML markup and files must be well formed. If the specified character vector or string scalar ends with .html, then it is assumed to be the path to an HTML file.

When embedding HTML markup, you do not need to specify <html> or <body> tags. If the markup you specify is supported in the Chromium browser used by MATLAB figures created with the uifigure function, then it will render. If you need more structure to your code, then consider using an HTML file instead.

If you set the HTMLSource property to the path to an HTML file, the HTML file must be located in a place that your local file system can access. If you are using supporting files, such as JavaScript, CSS, libraries, or images, then put the files in a location that your local file system can access, reference them in an HTML file, and set the HTMLSource property to the path to the HTML file. Supporting files cannot be in a relative directory adjacent to or above the HTML file.

Example: h = uihtml('HTMLSource','CustomCharts.html') specifies an HTML file.

Example: h = uihtml('HTMLSource','<p>This is <span style="color:red">red</span> text.</p>') specifies markup.

MATLAB data, specified as any MATLAB data type. Use this argument when the value of HTMLSource is the path to an HTML file defining a JavaScript object. Then, this data can be synchronized between the MATLAB HTML UI component and the JavaScript object.

To synchronize the value of the Data property between MATLAB and the third-party content that you are embedding in your app, create a setup function in an HTML file that connects a JavaScript object called htmlComponent to the HTML UI component in MATLAB. Then, set the HTMLSource property value to the path to the file.

Changes in the value of the Data property trigger callback events in only one direction. Specifically,

  • When the Data property is set in MATLAB, the Data property of the htmlComponent JavaScript object also updates and triggers JavaScript event listeners of the 'DataChanged' event.

  • When htmlComponent.Data is set in JavaScript, the Data property of the HTML UI component in MATLAB also updates and triggers the DataChangedFcn callback.

If you have data like nested cell arrays, arrays of structures, or MATLAB table array data, you might need more information about how data is converted between MATLAB and JavaScript. When the Data property of an HTML UI component is set in MATLAB, the data is converted using the jsonencode function, synchronized with JavaScript, parsed using JSON.parse(), and finally set to the Data property of the htmlComponent JavaScript object. Conversions happen in the opposite direction as well by way of JSON.stringify() and the jsondecode function. The Data property is the only property that synchronizes with JavaScript.

Refer to the jsonencode function for more information about the data types it supports. If the jsonencode function does not support your data type, then use a data type conversion function, like num2str, to convert your data to a supported type. Then, set it as the value of the Data property.

For more information about how to write an HTML file that enables data synchronization and the properties of the htmlComponent JavaScript object, see Create HTML File That Can Trigger or Respond to Data Changes.

Callback when data changes, specified as one of these values:

  • Function handle.

  • Cell array in which the first element is a function handle. Subsequent elements in the cell array are the arguments to pass to the callback function.

  • Character vector containing a valid MATLAB expression (not recommended). MATLAB evaluates this expression in the base workspace.

When the value of the Data property changes in the htmlComponent JavaScript object, the Data property of the MATLAB HTML UI component is updated, and this callback executes.

This callback function can access specific information about changes in data in the JavaScript object. MATLAB passes the information in a DataChangedData object as the second argument to your callback function. In App Designer, the argument is called event. You can query the DataChangedData object properties using dot notation. For example, event.PreviousData returns the previous value of Data before it was last updated or changed. The DataChangedData object is not available to callback functions specified as character vectors.

This table lists the properties of the DataChangedData object.

PropertyDescription
DataMost recent data resulting from the last DataChanged event
PreviousDataData before the last DataChanged event
Source

MATLAB HTML UI component that executes the callback

EventName'DataChanged'

For more information about writing callbacks, see Write Callbacks in App Designer.

Location and size of HTML UI component relative to the parent container, specified as a four-element vector of the form [left bottom width height]. This table describes each element in the vector.

ElementDescription
leftDistance from the inner left edge of the parent container to the outer left edge of the HTML UI component
bottomDistance from the inner bottom edge of the parent container to the outer bottom edge of the HTML UI component
widthDistance between the right and left outer edges of the HTML UI component
heightDistance between the top and bottom outer edges of the HTML UI component

The Position values are relative to the drawable area of the parent container. The drawable area is the area inside the borders of the container and does not include the area occupied by decorations such as a menu bar or title.

All measurements are in pixel units.

Limitations

  • You cannot link to URL web resources or embed applications from external web pages using the uihtml function.

  • HTML files that you specify for the HTMLSource property cannot access third-party JavaScript libraries by way of a Content Delivery Network (CDN). Save libraries in a location that your local file system can access.

  • Common web file types, like JavaScript and CSS, can be referenced from the HTML file you specify for the HTMLSource property, but other web file types might not be supported.

  • Content cannot overflow the bounds of the HTML UI component. If you are creating dynamic content, like pop-up widgets, make the size of your HTML UI component large enough to display the widget when the pop-up is in its opened state.

  • On MATLAB desktop, certain HTML features such as web plugins and access to webcams or microphones are not supported.

  • You cannot set the HTMLSource property to an HTML file that has query parameters appended to its file name. As a workaround, set these parameters in htmlComponent.Data.

  • Hyperlinks with matlab: operations are not supported.

More About

collapse all

Potential Security Risks

Note

This list is not intended to be comprehensive. Consult external resources for additional risks and security considerations when interfacing with third-party libraries.

Applications that interface with third-party JavaScript libraries are potentially vulnerable to data or code injection attacks.

  • MATLAB features like the eval function can increase the risk of injection attacks. As a countermeasure, validate untrusted input before using it in MATLAB.

  • Any MATLAB function that processes code-like input (XML, JSON, SQL, etc.) is potentially vulnerable to code injection.

  • Applications that access the operating system using the MATLAB system, dos, or unix functions might be vulnerable to code injection.

For information about how to reduce the potential risk to your deployed web apps, see Authoring Secure Web Apps (MATLAB Compiler).

Tips

  • If you are creating an HTML file to embed in your app, first verify that the static HTML renders properly in a browser. For more information, see Create HTML File That Can Trigger or Respond to Data Changes.

  • If you want to refresh the value of the HTMLSource property, use this workaround to save the original value of HTMLSource to a variable, reset HTMLSource it to an empty value and update the figure to clear its contents, and finally set HTMLSource back to its original value.

    oldValue = h.HTMLSource;
    h.HTMLSource = '';
    drawnow()
    h.HTMLSource = oldValue;

  • MATLAB figures created with the uifigure function use the Chromium browser and run HTML5. New Chromium versions are released frequently and can vary between operating systems. Consult external Chromium resources for supported features and functionality. Take this factor into consideration if you plan to share your app or use it in different environments.

  • Check external resources, like https://caniuse.com/, for the types of features that are supported across different desktop and web browsers.

  • MathWorks® does not promote any third-party libraries.

Introduced in R2019b