How to use the iframe postMessage API?

When embedding SharpTools.io dashboards within in an iframe, you can use the postMessage API on modern browsers to perform client-side navigation of your embedded SharpTools.io dashboards. This results in a more seamless navigation experience where you can quickly switch between dashboards without reloading the page.
This API is for when you have developed your own HTML page - for example, for building a custom navigation or integrating other web apps - and would like to include SharpTools.io in an embedded iframe.

If you are looking to use an iframe to embed other websites into your dashboard, check out the URL Custom Tiles.
Without the postMessage API, you can change the URL of iframe to point to a different dashboard URL, but this causes the full page to be reloaded, causes the navigation between dashboards to be slower, and takes the dashboard in and out of kiosk mode resulting in a less than ideal effect. 
The postMessage API solves this through the use of client side navigation. The required message format for the postMessage API is:
{action:'navigate', route: { path: '/dashboards/view/xxxxx'}}
For example:
<div id="app">
  <h1>Example External Page</h1>
  <a onclick="navigate('/dashboard/view/xxxxxx')">Dashboard 1</a> |
  <a onclick="navigate('/dashboard/view/yyyyyy')">Dashboard 2</a> |
  <a onclick="navigate('/dashboard/view/zzzzzz')">Dashboard 3</a>
  <iframe id="iframe" src="https://sharptools.io/dashboard/view/xxxxxx" style="width:100%;height:600px;"></iframe>
</div>
<script>
    function navigate(path){
      iframe.contentWindow.postMessage({action:'navigate', route: { path: path}}, "*")
    }
</script>
If you also want to support navigating to other websites and pages within an iframe, there are few options.
  1. Track if you are on SharpTools already - if so, send the postMessage to navigate between dashboards - otherwise just change the iframe src to do a full navigation.

    Example: https://codesandbox.io/s/mmrwjvz4jx
  2. Keep a separate iframe for navigating pages and separate iframe for showing SharpTools and hide/show them accordingly. That way SharpTools pages are always instantly loaded.*

    Example: https://codesandbox.io/s/w6p036j8rw
*In option 2, some people even create an iframe for each different site/domain... you get the appearance of instant page loading in that case, but use up more resources as every site is loaded at the start and stays loaded in the background. This works fine for simple pages you've created that aren't resource intensive, but can be a burden on small tablets if each page is loading a complex modern web app.
Did this answer your question? Thanks for the feedback There was a problem submitting your feedback. Please try again later.