The goal of this tututorial is to embed a Goo scene in an iframe, but make the Goo scene react to mouse movements outside the iframe.
To solve this problem, you need to know if you’re going to host the Goo scene on your own server (same-domain) or on the Goo cloud (cross domain).
|Same-domain iframe||Cross-domain iframe|
|Detect mouse inside iframe||window||window|
|Detect mouse outside iframe||window.parent||postMessage|
Solution 1: The “mousemove” event on the window
To track the mouse movement on a page, traditionally we use an event listener on the
window object. Let’s try this.
- Create a new scene in Create
- Add a box to the scene
- Add a Script component to the box entity.
- Create a Custom Script in the script component.
- Open the script in the Script editor.
- Enter the following code:
Now embed the scene in a HTML page:
Solution 2: Listening for “mousemove” on window.parent
Now let’s attach the listener on the correct Window object, by using
window.parent. Update the code so it looks like this:
Unfortunately, we now get the following error message:
Uncaught DOMException: Blocked a frame with origin "https://goote.ch" from accessing a cross-origin frame..
The browser automatically blocks the iframe from reaching out of its frame, because of security concerns. So how can we get around this? One option is to download the scene as a webpage, and put it on the same domain as the main webpage. If you do it this way, the browser will allow the iframe to “reach out” and not throw an error.
Solution 3: Using postMessage
Let’s say we would like to include a published Create scene in an
iframe, without having to put it in our own server. A solution we can use here is called
Change the HTML embed code so it looks like this:
Now, in our script we can listen to the
message event on the iframe window. Update the Goo Create script to this:
You will now notice that you get log messages both on the iframe and outside the iframe. Perfect!
Step 4: Change the color of a mesh depending on mouse position
console.log example is a bit boring, so let’s do something useful instead.
Update your HTML embed code to the following.
In the Create script, we want to set the diffuse color of the cube depending on the mouse position. Copy this code to the custom script:
Iframes makes it easy to embed a Goo Create scene into a webpage. Due to the security policies around iframes, one has to develop special solutions to communicate with the rest of the webpage, especially in the cross-origin case.