February 8, 2016

Appending div to iframe

Jesus Christ’s Question:

What is wrong with this piece of code:

jQuery('<iframe id="groundplan_popup" class="groundplan_hidden" />').appendTo("#popup_holder");
var iframe = jQuery("#groundplan_popup");
iframe.attr("src","::censored::" + filename);
var iframe_body = iframe.contents().find('body').append('<div id="groundplan_popup_exit"></div>');
var exit_btn_gp = iframe_body.append(jQuery("#groundplan_popup_exit"));

So i have to dynamically create an iframe element which will open up .pdf file in a popup and that part works. What I can’t manage to do is create a div with an id of “groundplan_popup_exit” within that iframe. I don’t know exactly why this doesnt’ work and what exactly I’m doing wrong. When i inspect the iframe window console brings out this warning:

/deep/ combinator is deprecated. See https://www.chromestatus.com/features/6750456638341120 for more
details.

Dont know if it has anything to do with the reason why this isn’t working.

EDIT:

This is what my code looks like now.
enter image description here

Console prtscr:
enter image description here

Iframe console elements prtscr:

enter image description here

So i’m basically confused about the whole situation as I’m not that experienced in using jquery in general and this is my first time using it with iframes. I’m not even sure if the #groundplan_popup_exit div is even created and how do I find it if it is.

I see some problems:

var iframe_body = iframe.contents().find('body').append('<div id="groundplan_popup_exit"></div>');

Here you are already appending the element to the body.

var exit_btn_gp = iframe_body.append(jQuery("#groundplan_popup_exit"));

After you have appended above, you are trying to append again with jQuery("#groundplan_popup_exit") which does not even exists.

Fix (untested) would be something like this:

var iframe_body = iframe.contents().find('body');
var exit_btn_gp = iframe_body.append('<div id="groundplan_popup_exit"></div>');
December 4, 2015

How to know if a page loaded via iframe is within sandbox?

Layke’s Question:

I’m trying to detect if a page is loaded via a sandboxed iframe. Is this possible?

For example,we provide custom embeddable widgets and some people think they are being smart by sandboxing them in their iframe, but this breaks certain things.. such as window.top.location

Obviously, they could enable the features we need, but ideally, I should be able to just do something like:

"sandbox" in window.top

I have also tried doing

try {
    // do something that would not work if within sandbox
} catch(e) {

}

But this doesn’t work because it’s a browser security error, and not related to javascript.

JSFiddle actually sandbox their iframes to prevent window.top.location navigation, so this would be a good example to show you.
If you look at this example here:

http://jsfiddle.net/mwsb8geL/show/

You can see the error when you press the Instant Book Online button.

enter image description here

A project sandblaster can help you detect if you running being sandboxed.

Inside the iframe where you are testing if it is sandbox, open up your script tag and paste the contents of https://raw.githubusercontent.com/JamesMGreene/sandblaster/master/dist/sandblaster.js. This is due to the security issue.

After this, its as simple as the following.

var result = sandblaster.detect();
if(result.sandboxed === true) {
    //sandboxed
}

Here is a demo I made for another answer but shows that the solution works.

Detect if JavaScript is Executing In a Sandboxed Iframe?

Omninternet’s Question:

I have a product that’s playing a video in Flash (if available), and falls back to HTML5 if Flash isn’t available.

I’m not able to find a way to determine if JavaScript is executing within an Iframe with the “sandbox” attribute, which is necessary for my solution because sandboxed iframes disable all plugins. The sandboxed iframe could be as simple as this:

<iframe src="http://www.cross-domain.com/" sandbox="allow-scripts">

To determine if Flash is enabled, I’m using swfobject’s method of checking navigator.plugins[“Shockwave Flash”].description, which is set even when in a sandboxed iframe. I can load the swf object, but it doesn’t play.

To reproduce this issue, visit http://jsfiddle.net/max_winderbaum/9cqkjo45/, open your chrome inspector and click “Run”. The script on the cross-domain site will pause in the context of the sandboxed iframe.

According to the W3 spec at http://dev.w3.org/html5/spec-preview/browsers.html#sandboxing-flag-set, there is supposed to be an “active sandboxing flag set” on the document that JavaScript can access (at least that’s how I’m reading the spec). There doesn’t seem to be any flag set on the iframe’s document.

Does anyone have any ideas / solutions on how to detect if JavaScript is executing from within a sandboxed iframe?

A project sandblaster can help you detect if you running being sandboxed.

Sandbox check if itself is framed first and then scans through the attributes of the frame element to detect several information about itself. These includes framed, crossOrigin, sandboxed, sandboxAllowances, unsandboxable, resandboxable, sandboxable.

To detect if itself is sandboxed in our case, it checks if the frame element has an attribute sandbox.

// On below `frameEl` is the detected frame element
try {
  result.sandboxed = frameEl.hasAttribute("sandbox");
}
catch (sandboxErr) {
  result.sandboxed = null;
  if (typeof errback === "function") {
    errback(sandboxErr);
  }
}

I tried to replicate your issue and to test if this solution works, I had to paste the script into the window itself due to the security issue.

<html>
    <head>
    </head>
    <body>

    <script>
        //Paste the contents of the script(https://raw.githubusercontent.com/JamesMGreene/sandblaster/master/dist/sandblaster.js) here

        var result = sandblaster.detect();
        if(result.sandboxed === true) {
            //sandboxed
        }
        debugger;
    </script>
    </body>
</html>

Here is a demo: http://jsfiddle.net/Starx/tzmn4088/ that shows this working.

August 29, 2013

How to change content of website loaded in iframe?

Ivan.daragan’s Question:

I need to change content of website using jQuery loaded in iframe from other domain such this:

<html>
  <head>
  </head>
  <body>
    <iframe src="site.com/somepage.html></iframe>
    <script>
      $('iframe').find('div#message').value('hello');
    </script>
  </body>
</html>

Also I added target link to whitelist.
Could any helps? Thanks.

Your script is running during runtime so it will not find the DOM of the iframe and will break. What you can do is create a function on your parent page like:

//On Your Parent page
function modifyIframeContent() {
     $('iframe').find('div#message').value('hello');
}

Then call this function from the iframe after it loads.

// On Your Iframe page
window.onload = function() {
    parent.modifyIframeContent();
}

Of course: Your iframe must be of same domain for this work.

February 26, 2013

Add click event to iframe

Question by user1170330

I want to add a click event to an iframe. I used this example and got this:

$(document).ready(function () {
   $('#left').bind('click', function(event) { alert('test'); });
});

<iframe src="left.html" id="left">
</iframe>

But unfortunately nothing happens.
When I test it with another element (e.g. a button), it works:

<input type="button" id="left" value="test">

Answer by Starx

The actual problem is that, the click event does not bind to the DOM of the iframe and bind() is deprecated, use .on() to bind the event. Try with the following codes and you will find the borders of the iframe clickable getting that alert.

$('#left').on('click', function(event) { alert('test'); });

Demo of that Issue

So how to get it done?

How you should do is, create a function on iframe page, and call that function from that iframe page.

April 28, 2012

Dynamically add options to a list through a hidden iframe

Question by user1157439

I want to dynamically add options to a list through a hidden iframe; I suspect my mistake is in the PHP below:

<?php echo 'var oInner  = document.createTextNode("'.$donnees["name"].'");'; ?>

because my code works perfectly with:

<?php echo 'var oInner  = document.createTextNode("Newoption");'; ?>

I don’t know why createtextnode doesn’t want to take my PHP var… I thought it could be a same origin policy since the database is located on a server outside my website.

I don’t know.

You’ll find enclosed the complete code:

In my HTML I have:

//select or change a country will trigger the javascript part
<select name="countrym" id="countrym" onchange="validcountry();">
    <option value"France">France</option>
</select>

//Empty region list
<select name="regionm" id="regionm">
</select>

//My Iframe
<iframe name="upload_iframe2" id="upload_iframe2" frameborder="0"></iframe>

In my Javascript I have:

//My function triggering the PHP through the Iframe
function validcountry() {
var countrym = document.getElementById('countrym');
    var choixco = countrym.options[countrym.selectedIndex].value;
    document.getElementById('upload_iframe2').src = 'region.php?choix='+choixco;

In my PHP region.php file, I have:

<?php

// Get my choice
$codepays = $_GET['choix'];

//Retrieve the regions corresponding to the country
$pdo_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
$bdd = new PDO(XXX);
$req = $bdd->prepare('SELECT name FROM regions WHERE country = :country');
$req->execute(array('country' => $codepays));
$donnees = $req->fetch();

while($donnees)
   {   
// I checked the format of the data (no problem so far)
echo var_dump ($donnees['name']);
?>

//I add an option through Javascript
<script language="JavaScript" type="text/javascript">
var oOption = document.createElement("option");

//Here is my big issue:
<?php echo 'var oInner  = document.createTextNode("'.$donnees["name"].'");'; ?>

oOption.value = "none";
oOption.appendChild(oInner);
var parDoc = window.parent.document;
var regionm = parDoc.getElementById("regionm");
regionm.appendChild(oOption);
</script> 

<?php
$donnees = $req->fetch();
}
$req->closeCursor();
exit();
?>

Answer by Starx

I am suspecting that the indexed element cannot be found. But is all cases, this below should work.

<?php echo 'var oInner  = document.createTextNode("'. (isset($donnees["name"]) ? $donnees["name"] : '') .'");'; ?>
March 25, 2012

PrettyPhoto – passing unique parameter from iframe window to parent page

Question by Gublooo

I’ve recently started using prettyphoto to display a video.

This is my current setup

<link rel="stylesheet" href="/css/prettyPhoto.css" type="text/css" media="screen" charset="utf-8" />
<script src="/js/jquery.prettyPhoto2.js" type="text/javascript" charset="utf-8">

<script type="text/javascript" charset="utf-8">
  $(document).ready(function(){
    var lastClicked = null;
    $("a[rel^='prettyPhoto']").prettyPhoto({
    callback: function()
    {           
        if(lastClicked != null) {
                var topicid = lastClicked.data("topicid"); 
                $.post('/course/close-video', {topic_id: topicid });
                lastClicked = null;
        }
    }
    }).click(function (){
        lastClicked = $(this);
});
</script>


<a data-topicid="<?php echo $topic->topic_id;?>" href="/course/play-video/topic_id/<?php echo $topic->topic_id;?>?iframe=true&width=470&height=340" rel="prettyPhoto" title="<?php echo $topic->topic_name;?>">
<img src="/images/videos/<?php echo $image_name;?>" width="170" height="103" alt="<?php echo $topic->topic_name;?>"/>
</a>

This is what is happening

1) When a user clicks on the link – the play-video php action is called which retrives the video url from database and passes so that it can be played on the popup window. This works fine.

2) Now the play-video also generates a unique id which is passed on to the page (iframe window) where the video is played. Right now I’m just displaying that value on the page. I can have that unique id stored as a hidden field or as a div value.

3) Now when the user closes this window – how can I access this unique id in the callback function of pretty photo which is in the main page.

Thanks a lot
Appreciate your time

Answer by Starx

Create a variable on the main page.

var UniqueId; //Unique ID that will arrive from the iframe

Now a function to write the value

function setUniqeId(val) {
    UniqueId = val;
}

Now inside the iframe, where the id, has already been receive, pass it to the parent like

parent.setUniqueId(TheIdThatIHaveReceived);

Update:

Make sure the script to read is after the DOM is loaded. One of the early ways of ensuring this, is placing the script after the Elements

<input id="topic_user_id" type="text" />
<script>
var unique_id = document.getElementById("topic_user_id").value;
parent.setUniqueId(unique_id);
</script>

One of the modern techniques would be to create a event handler like

window.onload = function() {
    var unique_id = document.getElementById("topic_user_id").value;
    parent.setUniqueId(unique_id);
};
March 19, 2012

Is there a way to check whether the html is loaded on Iframe

Question by AmGates

My problem is that I have two html files for example say 1.html and 2.html. The contents of the files are
1.html
It consists of the Iframe. The source of the Iframe is 2.html.
2.html
It is a sample html page.

My question is that I want to check whether the 2.html is loaded on an Iframe or loaded on a separate browser directly without putting it inside an Iframe. The checking has to be done from 2.html only.

Any suggestions friends.
Thanks in advance.

Answer by Sepehr

when loaded in iframe the window.parent points to the parent window, however when loaded in a separate window window.parent points to window itself:

var loadinInIframe = window.parent != window;

Answer by Starx

Bind a function inside the iframe’s onload event and set a loaded variable on the parent page

On the iframe

window.onload = function() {
   parent.iframeLoaded = true;
}

On the parent page, just declare the variable to hold the value

var iframeLoaded = false;

Now you can check this var when you need from the parent page like

if(iframeLoaded) {
    // Do something
}
March 6, 2012

Float over iframes html

Question by Ma9ic

Is it possible to float a nav bar over a iframe here is the code that i have so far?

the nav bar as you will be is in the html page and contains buttons that trigger the iframe to go to the next page etc.

Any ideas?

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Fraud Protection - Course</title>
<style>
    .backbutton[type="button"] {
        border: 0;
        background: url("back.png") no-repeat;
        text-indent: -9999em;
        line-height:3000;
        width: 100px;
        height: 35px;
        cursor:pointer;
    }
        .nextbutton[type="button"] {
        border: 0;
        background: url("next.png") no-repeat;
        text-indent: -9999em;
        line-height:3000;
        width: 100px;
        height: 35px;
        cursor:pointer;
    }
            .savebutton[type="button"] {
        border: 0;
        background: url("save.png") no-repeat;
        text-indent: -9999em;
        line-height:3000;
        width: 100px;
        height: 35px;
        cursor:pointer;
    }
</style>
</head>
<body>

    <iframe src="" width="100%" class="naviframe" id="contentFrame" hieght="100%"></iframe>
    <div id="navDiv">
     <input type="button" class="backbutton" id="butPrevious" onclick="doPrevious();" value="<- Previous"/>
        <input type="button" class="nextbutton" value="Next ->" img src="/images/Btn.PNG" id="butNext" onclick="doNext();"/>
        <input type="button" class="savebutton" value="Save Progress"  img src="/images/Btn.PNG" id="butExit" onclick="doExit();"/>
    </div>

</body>
</html>

Answer by Starx

It is possible. You have to position the element to be floated, as absolute with negative margin.

Demo

March 2, 2012

How to close iframe from inside iframe?

Question by Luca Frank Guarini

I’ve got a WordPress site where posts are loaded into an iframe.

This is the code that works:

<a class="trick" rel="<?php the_permalink() ?>" href="<?php the_permalink() ?>"><?php the_title(); ?></a>

$(document).ready(function(){

    $.ajaxSetup({cache:false});
    $(".trick").click(function(){
        var post_link = $(this).attr("rel");
        $("#frame").css("display","block");
        $("#frame").attr("url", post_link);
        $("body").css("overflow","hidden");
    });

  });         </script>
<iframe id="frame" frameborder="no" allowtransparency="true" width="100%" height="100%" scrolling="no" src=""></iframe>

Now, how to close this loaded iframe from inside the iframe?

The main page is index.php (main wordpress loop), the content of the iframe is single.php (single post) without header and footer.

Thanks.


This is what i’ve got in single.php

<head>

<script src="http://code.jquery.com/jquery-latest.js"></script>
    <script>
    $(document).ready(function(){
        $("#close").click(function(){
            $('#frame', window.parent.document).remove();

             });

        });

    </script>


</head> 

<body>
<div id="container-single">
    <button id="close" >Close</button>



    <?php if (have_posts()) : while (have_posts()) : the_post(); ?>

        <article <?php post_class('single') ?> id="post-<?php the_ID(); ?>">

            <h1 class="entry-title"><?php the_title(); ?></h1>

            <div class="entry-content">

                <?php the_content(); ?>

                <?php wp_link_pages(array('before' => 'Pages: ', 'next_or_number' => 'number')); ?>

                <?php the_tags( 'Tags: ', ', ', ''); ?>

                <?php include (TEMPLATEPATH . '/_/inc/meta.php' ); ?>

            </div>


        </article>



    <?php endwhile; endif; ?>

    </div>

</body>

Answer by Starx

I know a little trick actually.

Make a function on your parent page

var closeIFrame = function() {
     $('#iframeid').remove();
}

Inside the iframe you want to close call from anywhere you want

parent.closeIFrame();

Tricky, isn’t it?

...

Please fill the form - I will response as fast as I can!