Get the class of an element clicked upon in an iframe? - javascript

How can I get the class of an element clicked upon in an iframe?
HTML:
<input id="tag" type="text">
<iframe id="framer" src="SameDomainSamePort.html"></iframe>
JS:
$(document).ready(function () {
$("iframe").each(function () {
//Using closures to capture each one
var iframe = $(this);
iframe.on("load", function () { //Make sure it is fully loaded
iframe.contents().click(function (event) {
iframe.trigger("click");
});
});
iframe.bind("click", function(e) {
// always returns the iframe rather than the element selected within the iframe...
$("#tag", window.top.document).val($(e)[0].target.className);
return false;
});
});
});
Would it be easier to inject js?
And could I add css as well?
All help is appreciated!

Here should be enough tools to do what you want
Also the load event cannot be used unless you set the src later, because it has already triggered when you run your code
The fiddle works: https://jsfiddle.net/mplungjan/kqeqzusf/
SO have more stringent sandbox issues but also look at
SecurityError: Blocked a frame with origin from accessing a cross-origin frame
$(function() {
$(".iframe").each(function(i) {
var doc = $(this)[0].contentWindow.document;
var $body = $('body',doc);
$body.html(`<div id="test${i}">Click me ${i}</div>`); // or set the source
$body.on("click",function(e) { // assign a handler
console.log(e.target.id);
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div id="container">
<iframe id="iframe1" class="iframe"></iframe>
<iframe id="iframe2" class="iframe"></iframe>
</div>
More:
putting html inside an iframe (using javascript)
jQuery/JavaScript: accessing contents of an iframe
jQuery/JavaScript: accessing contents of an iframe
[jQuery]Find click inside an iFrame

Related

Append within Append, Iframe within Append in Jquery

I've looked at
Insert content into iFrame and their fiddle at http://jsfiddle.net/8VP4y/3/ to come out with the following codes which i'm having problem.
i've created a jsfiddle for my problem below.
https://jsfiddle.net/cy87j70t/2/
$( document ).ready(function() {
$('#card2').html( '<iframe id="myFrame"></iframe>' );
var myFrame = $("#myFrame").contents().find('body');
var myFrame2 = $("#myFrame2").contents().find('body');
myFrame.append('<p>OH NO TOKEN IS FOR myFrame Original ');
myFrame2.append('<p>OH NO TOKEN IS FOR myFrame 2 ');
});
AND the HTML looks like this;
<div id='card2'>
</div>
<iframe id='myFrame2'>
</iframe>
I'm trying to create a iframe using javascript, then writing to the iframe with content from JSONP (i've ommitted that part for easy debug);
I'm not sure why it's not writing to the iframe, is it because the iframe is created by javascript?
I've tried append, html, after, prepend but nothing seems to allow me to write to the iframe
No, it's not a bug.
Updated jsfiddle
The right way is:
$(function () {
$('#card2').html('<iframe id="myFrame"></iframe>');
// add the src attribute so that the load event will take place in every browser..
$("#myFrame").attr('src', 'about:blank');
// wait for the iframe is loaded
$("#myFrame").on('load', function(e) {
var myFrame = $("#myFrame").contents().find('body');
myFrame.append('<p>11111111OH NO TOKEN IS FOR myFrame Original</p>');
});
var myFrame2 = $("#myFrame2").contents().find('body');
myFrame2.append('<p>2222222222 OH NO TOKEN IS FOR myFrame 2</p>');
});
<script src="https://code.jquery.com/jquery-1.12.1.min.js"></script>
<div id='card2'>
</div>
<iframe id='myFrame2'>
</iframe>

Remove current iframe

I have an HTML page that opens an IFRAME ... But at some point, after some user interactions with the IFRAME, it should close itself. I've tried various commands such as:
var fram = $("IFRAME_NAME");
fram.parentNode.removeChild(fram);
this.remove();
this.style.display='none';
var frame = parent.frames['IFRAME_NAME'];
frame.remove();
frame.html("");
document.IFRAME_NAME.document.body.innerHTML = '';
Thanks.
Considering markup like this:
<iframe id="myframe" />
The following jQuery code will remove it in the host page:
$("#myframe").remove();
To close the iframe from within iframe itself, define the function in the host page:
function closeFrame() {
$("#myframe").remove();
}
Then in the code running in the iframe, call:
parent.closeFrame();
If you are using jQuery (and I've understood your question properly), you can use a code as simple as:
<iframe src="http://www.google.com" id="testframe"></iframe>
<script>
$(document).ready(function() {
setTimeout(function () {
$('#testframe').remove();
},5000);
});
</script>
http://jsfiddle.net/pYHx5/

How to add a click event to p elements in iframe (using jQuery)

How to add a click event to <p> elements in iframe (using jQuery)
<iframe frameborder="0" id="oframe" src="iframe.html" width="100%" name="oframe">
There's a special jQuery function that does that: .contents(). See the example for how it's works.
Your best best bet is to invoke the iframe AS LONG AS it's part of your domain.
iframe.html
<html>
<head>
<script>
window.MyMethod = function()
{
$('p').click();
}
</script>
</head>
<body></body>
</html>
And then use
document.getElementById('targetFrame').contentWindow.MyMethod();
To invoke that function.
another way is to access the iframe via window.frames.
<iframe name="myIframe" src="iframe.html"/>
and the javascript
child_frame = window.frames['myIframe'].document;
$('p',child_frame).click(function(){
alert('This click as bound via the parent frame')
});
That should work fine.
Wanted to add this, as a complete, copy-paste solution (works on Firefox and Chrome). Sometimes it is easy to miss to remember to call the event after the document, and so the iframe, is fully loaded:
$('#iframe').on('load', function() {
$('#iframe').contents().find('#div-in-iframe').click(function() {
// ...
});
});
The iframe must be on the same domain for this to work.
By giving a reference to the IFrame document as the second parameter to jQuery, which is the context:
jQuery("p", document.frames["oframe"].document).click(...);
To access any element from within an iframe, a simple JavaScript approach is as follows:
var iframe = document.getElementById("iframe");
var iframeDoc = iframe.contentDocument || iframe.contentWindow;
// Get HTML element
var iframeHtml = iframeDoc.getElementsByTagName("html")[0];
Now you can select any element using this html element
iframeHtml.getElementById("someElement");
Now, you can bind any event you want to this element. Hope this helps. Sorry for incorrect English.

Problem with iframe reading it

Is there a equivalent of jQuery live function inside prototype? I have a iframe which is dynamically loaded into dom, and I need to access elements inside iframe and I can't. I need to do something when certain element inside iframe is hovered, how can I do that with prototype or native js?
Assuming your iframeid is iframe_id and the link inside the iframe's id is iframe_link, heres a prototype script that will alert "hover" when the link inside the iframe is rolled over:
<script>
var $IFRAME = function (id){
return $('iframe_id').contentWindow.document.getElementById(id);
}
function watch_iframe(){
var x = $IFRAME('iframe_link_id');
x.observe('mouseover', function(event) {
alert('hover')
});
}
window.setTimeout(watch_iframe,1000);//makes sure iframe is loaded before intiating the watch_iframe function
</script>
credit where it's due: What is the way to access IFrame's element using Prototype $ method
Here is a DOM way, if your IFRAME is on the same domain:
In your parent page:
<iframe src="iframeContent.html"></iframe>
<script>
function listen(elm){
alert(elm.tagName + ' moused over');
}
</script>
In your iframe content:
<div onmouseover="top.listen(this)">
mouse over me!
</div>

Capture iframe load complete event

Is there a way to capture when the contents of an iframe have fully loaded from the parent page?
<iframe> elements have a load event for that.
How you listen to that event is up to you, but generally the best way is to:
1) create your iframe programatically
It makes sure your load listener is always called by attaching it before the iframe starts loading.
<script>
var iframe = document.createElement('iframe');
iframe.onload = function() { alert('myframe is loaded'); }; // before setting 'src'
iframe.src = '...';
document.body.appendChild(iframe); // add it to wherever you need it in the document
</script>
2) inline javascript, is another way that you can use inside your HTML markup.
<script>
function onMyFrameLoad() {
alert('myframe is loaded');
};
</script>
<iframe id="myframe" src="..." onload="onMyFrameLoad(this)"></iframe>
3) You may also attach the event listener after the element, inside a <script> tag, but keep in mind that in this case, there is a slight chance that the iframe is already loaded by the time you get to adding your listener. Therefore it's possible that it will not be called (e.g. if the iframe is very very fast, or coming from cache).
<iframe id="myframe" src="..."></iframe>
<script>
document.getElementById('myframe').onload = function() {
alert('myframe is loaded');
};
</script>
Also see my other answer about which elements can also fire this type of load event
Neither of the above answers worked for me, however this did
UPDATE:
As #doppleganger pointed out below, load is gone as of jQuery 3.0, so here's an updated version that uses on. Please note this will actually work on jQuery 1.7+, so you can implement it this way even if you're not on jQuery 3.0 yet.
$('iframe').on('load', function() {
// do stuff
});
There is another consistent way (only for IE9+) in vanilla JavaScript for this:
const iframe = document.getElementById('iframe');
const handleLoad = () => console.log('loaded');
iframe.addEventListener('load', handleLoad, true)
And if you're interested in Observables this does the trick:
import { fromEvent } from 'rxjs';
const iframe = document.getElementById('iframe');
fromEvent(iframe, 'load').subscribe(() => console.log('loaded');
Note that the onload event doesn't seem to fire if the iframe is loaded when offscreen. This frequently occurs when using "Open in New Window" /w tabs.
Step 1: Add iframe in template.
<iframe id="uvIFrame" src="www.google.com"></iframe>
Step 2: Add load listener in Controller.
document.querySelector('iframe#uvIFrame').addEventListener('load', function () {
$scope.loading = false;
$scope.$apply();
});
You can also capture jquery ready event this way:
$('#iframeid').ready(function () {
//Everything you need.
});
Here is a working example:
http://jsfiddle.net/ZrFzF/

Categories

Resources