What is the process for integrating three.js code manually into an iframe?

I recently posted a question on Stack Overflow inquiring about how to input code into an iframe without using a file or URL. While I was successful with simple cases like <h1>Hello World</h1>, my ultimate goal is to integrate three.js into these iframes. Below is the approach I took to add code to the iframe:

var iframe = document.getElementById("my-iframe");
var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;

iframeDocument.body.innerHTML = "<h1>Hello World</h1>";

While this method worked flawlessly, my next step was to create a very basic three.js scene just as a starting point. Here's the snippet of code I attempted:

generatedCode = `\
    <!DOCTYPE html>\
    <html>\
        <head>\
            <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r134/three.min.js" ></script>\
        </head>\
        <body style="margin: 0;">\
            <script>\
        var scene = new THREE.Scene();\
        var camera = new THREE.PerspectiveCamera(90, window.innerWidth/window.innerHeight, 0.1, 1000);\
        \
        var mesh = new THREE.Mesh(\
            new THREE.BoxGeometry(1,1,1),\
            new THREE.MeshBasicMaterial({color:0xff0000})\
        );\
        \
        scene.add(mesh);\
        \
        camera.position.z = -5;\
        camera.lookAt(0, 0, 0);\
        \
        var renderer = new THREE.WebGLRenderer();\
        renderer.setSize(window.innerWidth, window.innerHeight);\
        document.body.appendChild(renderer.domElement);\
    \
    function animate(){\
        requestAnimationFrame(animate);\
        renderer.render(scene, camera);\
    }\
    \
    animate();\
        </script>\
        </body>\
    </html>\
    `

After defining this variable, I attempted to apply it in the same manner as before:

var iframe = document.getElementById("my-iframe");
var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;

iframeDocument.body.innerHTML = generatedCode; //Now utilizing the variable instead of a heading

However, this did not yield the desired results. Any insights on why this didn't work would be greatly appreciated. Thank you!

Answer №1

If you encounter the error message "Unterminated template literal" while using your generatedCode, it is recommended to escape or replace instances of </script> with <\/script>

Since your variable starts with

<!DOCTYPE html><html>
, it is advisable to construct the iframe using iframeDocument.write(). This allows you to use iframeDocument.body.innerHTML to write content within the <body> tag

To see the code in action, you can run it on jsfiddle

let generatedCode = `
<!DOCTYPE html>
<html>

<head>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r134/three.min.js"><\/script>
</head>

<body style="margin: 0;">
    <script>
        var scene = new THREE.Scene();
        var camera = new THREE.PerspectiveCamera(90, window.innerWidth / window.innerHeight, 0.1, 1000);
        var mesh = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), new THREE.MeshBasicMaterial({
            color: 0xff0000
        }));
        scene.add(mesh);
        camera.position.z = -5;
        camera.lookAt(0, 0, 0);
        var renderer = new THREE.WebGLRenderer();
        renderer.setSize(window.innerWidth, window.innerHeight);
        document.body.appendChild(renderer.domElement);

        function animate() {
            requestAnimationFrame(animate);
            renderer.render(scene, camera);
        }
        animate();
    <\/script>
</body>

</html>`;

var iframe = document.getElementById("my-iframe");
var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;

iframeDocument.write(generatedCode);
iframeDocument.close();
<iframe id="my-iframe"></iframe>

Answer №2

When an iframe element is coded within the same origin as its parent window, it can access the parent window using window.parent. Additionally, nested iframes can access the top most window in the hierarchy with window.top. Global variables declared with var can also be accessed as window properties.

In the following example, document.write is used to test if the script written to the iframe document is compiled successfully - although there may be alternative methods to achieve this. The script calls a test function in the parent iframe, which logs text on the console.

This code does not work on Stack Overflow due to a same-origin policy error, but functions as expected when loaded in a browser:

<!DOCTYPE html>
<html><head><meta charset="utf-8">
   <title>Iframe Access</title>
</head>
<body>
<h1>Parent window</h1>

<iframe id="my-iframe"></iframe>


<script>"use strict";
  var test = ()=>console.log("test() call in parent window");
  var iframe = document.getElementById("my-iframe");
  var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
  iframeDocument.open();
  iframeDocument.write( `
    <h1>iframe Body</h1>
    Check the console for output...
    <script>
      console.log(window.parent);
      window.parent.test();
   <\/script>`
  );
  iframeDocument.close();
</script>
</body>
</html>


Revisiting the question, a potential approach from the parent frame could be

iframe.contentWindow.generateContent = generateContent

This would assign generateContent as a property of the window within the iframe. However, it does not guarantee that generateContent will execute under these circumstances!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best approach to synchronize checkboxes with boolean values in my data model?

I've spent hours searching through similar questions, but haven't found a solution that perfectly matches my issue. What I need is to have a checkbox automatically checked based on a true/false value in my data using data binding. While I can suc ...

Retrieve telephone number prefix from Cookies using React

Being able to retrieve the ISO code of a country is possible using this method: import Cookies from 'js-cookie'; const iso = Cookies.get('CK_ISO_CODE'); console.log(iso); // -> 'us' I am curious if there is a method to obt ...

Place items at the lower part of the container rather than the top

My <ul> has a fixed height and I want the <li> elements inside it to stack at the bottom instead of the top. I attempted using vertical-align: bottom on the <ul>, but that didn't have any effect. The <li> content may overflow ...

Preventing Content Changes When Ajax Request Fails: Tips for Error Checking

I was struggling to find the right words for my question -- My issue involves a basic ajax request triggered by a checkbox that sends data to a database. I want to prevent the checkbox from changing if the ajax request fails. Currently, when the request ...

Unexpected behavior with VueJS Select2 directive not triggering @change event

Recently, I implemented the Select2 directive for VueJS 1.0.15 by following the example provided on their official page. However, I am facing an issue where I am unable to capture the @change event. Here is the HTML code snippet: <select v-select="ite ...

Update the content on the webpage to display the SQL data generated by selecting options from various dropdown

My database table is structured like this: Name │ Favorite Color │ Age │ Pet ────────┼────────────────┼───────┼─────── Rupert │ Green │ 21 │ ...

Express 4 does not support Angular ngRoute

I am trying to set up client-side routes using Angular along with Express 4. I have successfully used the ngView directive as per the guide ngView without Express, but once I enable Express routing, ngRoute stops working. How can I configure Express to wor ...

Tips for structuring commands in Discord.js

I'm in the process of restructuring my bot's commands. I currently have a folder called commands with all my commands inside, but I want to make it more organized by categorizing them into moderators, fun, and global like this: commands > mo ...

``Do not forget to close the modal window by clicking outside of it or

I am looking for a way to close the modal window either when a user clicks outside of it or presses the escape key on the keyboard. Despite searching through numerous posts on SO regarding this issue, I have been unable to find a solution that works with ...

Tips for selecting a specific input field in a ReactJS component with multiple inputs

I am currently developing a ReactJS application where I have implemented a component responsible for generating an HTML table. Within this component, I utilize Map to create rows using a child component. These rows contain multiple input fields that users ...

Is there a way to execute a javascript function that is located outside of my Angular application without having to import it?

I need to be able to trigger a JavaScript function that is located outside of my Angular app when a button is clicked. Unfortunately, it seems that importing the JavaScript directly into my Angular app isn't feasible for this task. The platform I am ...

Using Vue to alter data through mutations

Greetings! I am currently in the process of developing a website for storing recipes, but as this is my first project, I am facing a challenge with modifying user input data. My goal is to create a system where each new recipe added by a user generates a u ...

Encountered a problem when trying to import the function "createToken" into a Node.js middleware

I have developed a model called users in which I included a method named generateToken for generating web tokens. This model is being used with the Sequelize ORM. module.exports = (sequelize, Sequelize) => { const Tutorial = sequelize.define("u ...

Step-by-Step Guide: Unveiling a Particular Modal Post-Submission of Form with

My website has a form inside a modal, and when the form is submitted, I don't want the modal to close. However, I have encountered an issue because my SQL UPDATE statement redirects to the same page after updating the database. This disrupts the funct ...

Functional Components with Methods in ReactJS

When creating a functional stateless component that requires methods to access props, is there a recommended approach or best practice to follow? For instance: function Stateless(props) { function doSomething(props) { console.log(props); } ...

Is it possible to use jQuery to highlight HTML tags within a textarea field?

Is there a simple method using jQuery to highlight html-tags in red within a textarea? I'm clueless about how to achieve this since HTML tags aren't allowed in textarea, correct? :( Alternatively, can someone provide me with some helpful resour ...

Utilize Materialize css with Aurelia for dynamic styling

Looking to incorporate a Materialize CSS select dropdown in the template file order.html. The code snippet is as follows: <div class="row"> <div class="input-field col s12"> <select multiple> <option value="" dis ...

What is the best way to utilize the forEach method in React to manipulate a navigation element containing multiple links?

Here is the code I'm trying to convert: document.addEventListener("scroll", function() { const links = document.querySelectorAll(".nav-link"); for (const l of links) l.classList.toggle('scrolling', window.scrollY &g ...

Is it possible to conduct HTML-based Selenium tests without an internet connection?

As a newcomer to Selenium, I am currently using the Selenium IDE which has led me to create table structures like the one below: <table cellspacing="1" cellpadding="1" border="1" name="SELENIUM-TEST"> <thead> <tr class="title"> ...

Tips for keeping a div visible while hovering over a link using only CSS

Apologies for any language errors in advance. I will do my best to explain my issue accurately: In my CSS, I have created a hidden div that is displayed none by default. When I hover over a link in the navigation bar, I change the display to block, creati ...