Permission denied when implementing JavaScript within an iframe from the parent page - javascript

I am trying to implement JavaScript within an iframe from the parent page. I read Invoking JavaScript code in an iframe from the parent page, however, get the following error.
Error: Permission denied to access property "showIt"
document.getElementById('targetFrame').contentWindow.showIt();
I've tried implementing this both on jsfiddle as well as my server (don't know if it matters, but it uses https), but get the same results. I've also tried removing the $(function(){}) wrapper on the child iframe, but no change.
My actual application is described below.
How can this be accomplished?
My Application:
I have my parent page https://jsfiddle.net/5f4ct5ph/6/) which contains an iframe.
<iframe width="100%" height="300" src="https://jsfiddle.net/5f4ct5ph/5/embedded/result/" id="targetFrame"></iframe>
<button id="show">Show</button>
<button id="hide">Hide</button>
$(function () {
$('#show').click(function () {
document.getElementById('targetFrame').contentWindow.showIt();
});
$('#hide').click(function () {
document.getElementById('targetFrame').contentWindow.hideIt();
});
});
The iframe page (https://jsfiddle.net/5f4ct5ph/5/) contains a tinymce editor.
<div id="content">Initial content goes here</div>
#content {height:200px;width:400px;border: 1px solid;}
$(function () {
tinymce.init({
selector: "#content",
width : 400,
height: 200,
setup : function(ed) {
ed.on('init', function(e) {
e.target.hide();
});
}
});
function showIt() {
tinymce.get('content').show();
};
function hideIt() {
tinymce.get('content').hide();
};
});

fiddle.jshell.net (the parent document domain) is different to jsfiddle.net (your iframe domain).
I've changed your code to point to the jshell.net url instead (You can get this by using the URL of the frame in the bottom right of jsfiddle rather than the address bar).
https://jsfiddle.net/GarryPas/5f4ct5ph/7/
showIt() and hideIt() don't seem to be defined (because they are inside an anonymous function). Change this:
$(function () {
...
function showIt() {
tinymce.get('content').show();
};
function hideIt() {
tinymce.get('content').hide();
};
});
To this:
$(function () {
...
});
function showIt() {
tinymce.get('content').show();
}
function hideIt() {
tinymce.get('content').hide();
}
Then remove my alerts and put back your original code which I commented out.

Normally, if iframe and parent are on same domain, it should work, but there are restriction to communication from window to window. You can try using postMessage, like this:
In your parent page, in the click event, instead of calling the function directly, you could do this:
child_window = document.getElementById('targetFrame').contentWindow;
child_window.postMessage("showit" or "hideit", your_domain);
The in you iframe:
window.addEventListener("message", check_message, false);
function check_message(event){
switch(event.data){
case "showit":
showIt();
break;
case "hideit":
hideIt();
break;
default:
breaks;
}
Make sure your functions showIt and hideIt are available from where you call check_message.
Again, there may be another problem, it's hard to tell with the embedded jsfiddle, but in any case, when dealing with iframes and javascript, postMessage is often more flexible and secure than accessing functions and variables directly.

Related

jQuery - iframe inside iframe - ready vs load

Lets say I have the following:
default.asp:
<iframe src="frameOne.asp" id="myframeOne"></iframe>
frameOne.asp:
<iframe src="frameTwo.asp" id="myframe"></iframe>
frameTwo.asp:
<div id="hello">Test text</div>
Why does the following doesn't work (#1):
$("#myframeOne").load(function () {
$('#myframeOne').contents().find('#myframeTwo').load(function(){
$('#myframeOne').contents().find('#myframeTwo').contents().find('#hello').css('background-color','blue');
});
});
And this does apply the CSS?(#2):
$("#myframeOne").load(function () {
$('#myframeOne').contents().find('#myframeTwo').ready(function(){
$('#myframeOne').contents().find('#myframeTwo').contents().find('#hello').css('background-color','blue');
});
});
And this one doesn't(#3):
$("#myframeOne").ready(function () {
$('#myframeOne').contents().find('#myframeTwo').ready(function(){
$('#myframeOne').contents().find('#myframeTwo').contents().find('#hello').css('background-color','blue');
});
});
As I understand the .load waits until the content of the iframe is loaded, so I don't quite understand why it behaves differently on the frames (why it works when apply on the outer frame, but not in the inner frame).
With iframes I work always with the load function. I've got problems with the ready function too so try to work with the load function.

Stop All Code Execution Until IFrame Completely Loads

I am loading a webform and on this page I have an iFrame How can I delay the next line of my code from executing until the iFrame has completely loaded? I tried this javascript but it does not wait until the iFrame is totally rendered.
<script type="text/javascript">
document.getElementById('frame1').onload = function () {
}
EDIT
using the syntax below it writes the code to my window instead of actually executing it?
$( document ).ready(function() {
document.getElementById('frame1').onload = function () {
myWindow.close();
window.returnValue = true;
window.close();
}
});
Would it be possible to send a response to my client side C# code once the iFrame has fully loaded and I run my close() function from there?
You can use jQuery library
Wrap you function with this:
$( document ).ready(function() {
document.getElementById('frame1').onload = function () {
}
});
Don't forget to add jQuery library to your application. You can use the online one provided by Microsoft.
<head><script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.12.0.min.js"></script></head>

actions within the iframe breaks my script jQuery

i have a script that cuts a part of the iframe( iframe without headers ) and shows it. my problem is if i make actions within this iframe, the iframe reloads but is not applying the jquery filtering to give me only that part but instad gives me all the page with headers so i'm assuming that script is not working when it reload the iframe without the window reload of the main page that has the iframe:
<iframe class="test" width="100%" height="100%" src="/message.html?msjId=260" style="height:100%;width:100%;">
$(window).load(function () {
$('.test').each(function(){
var filteredContents1 = $(this).contents().find('.div_iframe').html();
$(this).contents().find('body').html(filteredContents1);
});
});
any solutions please ?
I think you need to add load events for frames as well. Add the load event in document.ready function as given below. If it works you may be able to omit window load event you already have for filtering frames data.
$(document).ready(function(){
$('.test').load(function () {
var filteredContents1 = $('#frame1').contents().find('#divChild').html();
$('#frame1').contents().find('body').html(filteredContents1);
});
});
Update on request of questioner
$(document).ready(function(){
$('.test').load(function () {
$('#frame1, #frame2, #frame3').each(function(){
var filteredContents1 = $(this).contents().find('#divChild').html();
$(this).contents().find('body').html(filteredContents1);
});
});
});
.

Jquery manage local script with full ajax site

Basically my app work like that :
Index.php manage call to other pages.
Each page contains 2 function onLoad() and onClose() which are redefined in each page
Index.php call the pages and execute the onLoad
Basically, i preload the page in a hidden div, i execute the predefined $.onLoad function and the i put the loaded content into a visible div
My question is only about the onLoad() scope, i want to remove code from the jquery eval seq when i change page, but i need a way to define it in the page.php file without knowing the container
The eval/seq is probably the eval queue of jquery, can't found info about that, just obtain with firebug...
In 2 words, i would like to be able to remove injected dom and script when i change context (pages)
index.php
$.onLoad = function() {}
$("#blabla").onChange(function() {
$("#data_iframe").load(chaineUrl, {}, function(responseText, textStatus, XMLHttpRequest) {
$("#data_iframe").ready(function() {
$("#data_div").children().remove();
$.onLoad();
$("#data_iframe").children().hide().appendTo($("#data_div")).show(); $("#data_iframe").children().remove();
$.onLoad = undefined;
}
});
});
page.php
<script>
$.onClose = (function(){
$('#container').blablabla();
//alert("test");
});
$.onLoad = (function(){
$('#container').blablabla();
}
</script>
The problem is that the jquery EVAL/SEQ keep growing each time a page is opened
and there are some side-effect like calling multiple time a function...
I guess its a scope problem so can you help me correct my code
(i've try with or without the $ but doesn't change anything)
just for information
<div id="data_div"></div>
<div id="data_iframe"></div>
Thanks
I usually use $(document).ready instead of onload. No need to do the "onload" trigger in load complete function. The ready function within the page.php will do the same job.
And how about direct load into data_div?
index.php
$("#blabla").onChange(function() {
$("#data_div").load(page.php);
});
page.php
<script>
$(document).ready(function() {
$('#container').blablabla();
});
</script>
I didn't try page close function before, may be it is not what you want. But you can try:
<script>
$(document).ready(function() {
$('#container').blablabla();
$(window).unbind('unload');
$(window).unload(function(){
$('#container').blablabla();
//alert("test");
})
});
</script>

jQuery iframe load() event?

Does anyone know if there is such a thing?
I have a iframe that's being inserted with $.ajax() and I want to do some stuff after the contents from the iframe are completely loaded:
....
success: function(html){ // <-- html is the IFRAME (#theiframe)
$(this).html(html); // $(this) is the container element
$(this).show();
$('#theiframe').load(function(){
alert('loaded!');
}
....
it works, but I see the IFRAME is loaded twice (the alert also shows twice).
use iframe onload event
$('#theiframe').on("load", function() {
alert(1);
});
If possible, you'd be better off handling the load event within the iframe's document and calling out to a function in the containing document. This has the advantage of working in all browsers and only running once.
In the main document:
function iframeLoaded() {
alert("Iframe loaded!");
}
In the iframe document:
window.onload = function() {
parent.iframeLoaded();
}
Along the lines of Tim Down's answer but leveraging jQuery (mentioned by the OP) and loosely coupling the containing page and the iframe, you could do the following:
In the iframe:
<script>
$(function() {
var w = window;
if (w.frameElement != null
&& w.frameElement.nodeName === "IFRAME"
&& w.parent.jQuery) {
w.parent.jQuery(w.parent.document).trigger('iframeready');
}
});
</script>
In the containing page:
<script>
function myHandler() {
alert('iframe (almost) loaded');
}
$(document).on('iframeready', myHandler);
</script>
The iframe fires an event on the (potentially existing) parent window's document - please beware that the parent document needs a jQuery instance of itself for this to work. Then, in the parent window you attach a handler to react to that event.
This solution has the advantage of not breaking when the containing page does not contain the expected load handler. More generally speaking, it shouldn't be the concern of the iframe to know its surrounding environment.
Please note, that we're leveraging the DOM ready event to fire the event - which should be suitable for most use cases. If it's not, simply attach the event trigger line to the window's load event like so:
$(window).on('load', function() { ... });
That's the same behavior I've seen: iframe's load() will fire first on an empty iframe, then the second time when your page is loaded.
Edit: Hmm, interesting. You could increment a counter in your event handler, and a) ignore the first load event, or b) ignore any duplicate load event.
Without code in iframe + animate:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script language="javascript" type="text/javascript">
function resizeIframe(obj) {
jQuery(document).ready(function($) {
$(obj).animate({height: obj.contentWindow.document.body.scrollHeight + 'px'}, 500)
});
}
</script>
<iframe width="100%" src="iframe.html" height="0" frameborder="0" scrolling="no" onload="resizeIframe(this)" >
You may use the jquery's Contents method to get the content of the iframe.
If you want it to be more generic and independent, you can use cookie. Iframe content can set a cookie. With jquery.cookie and a timer (or in this case javascript timer), you can check if the cookie is set each second or so.
//token should be a unique random value which is also sent to ifame to get set
iframeLoadCheckTimer = window.setInterval(function () {
cookieValue = $.cookie('iframeToken');
if (cookieValue == token)
{
window.clearInterval(iframeLoadCheckTimer );
$.cookie('iframeToken', null, {
expires: 1,
path: '/'
});
}
}, 1000);

Categories

Resources