Adam Mikacich Adam Mikacich - 1 year ago 43
Javascript Question

Run JavaScript Function in a different HTML file inside a script tag

Currently I have two HTML files. One named index.html and another called editor.html

Inside index.html I have an iframe of editor.html Above this iframe is also a notification system I made. To run a notification it uses a function I created which can be used like so:


This function works great when I call it from inside of the index.html since the function modifies the index.html's html code (via .innerHTML). An issue shows up when I try and call it from the editor.html

Even with the editor.html added into index.html like this at the top of index.html:

<script src="editor.html"></script>

And I wrote this in the editor.html:

<script src="index.html"></script>

When I try and run the Notification function from the editor.html there is an error since the function is inside the index.html and modifies index.html, not editor.html.

Keep in mind that in each of the index.html and editor.html the javascript is in a tag because there is other html within the file. Thanks and please ask questions if you need further confirmation.

Answer Source

This works fine if the iframe and the container are in the same domain.

First you should put the shared JavaScript code in a single external file, like main.js:

function Notification( msg )
    var div = document.getElementById("notification-div") ;
    div.innerHTML = msg ;
    /* The important thing is make this to be the container window when
     * Notification is called, so document is the desired one.

In index.html you should have the iframe and a div to print the notification text:

<div id="notification-div"></div>
<iframe src="editor.html" width=300 height=200></iframe>

Then include main.js in index.html and editor.html:

<script type="text/javascript" src="main.js"></script>

In index.html you can call it directly, as long as this is window:

Notification( "From index.html" ) ;
/* window will be this in the Notification function, so the call to
 * document.getElementById, will actually be window.document.getElementById

In editor.html you can refer to the container window object as top. So this call will give the desired result:

top.Notification( "From editor.html" ) ;
/* top will be this in the Notification function, so the call to
 * document.getElementById, will actually be top.document.getElementById