how to close Iframe using paremt post message in javascript - javascript

I have a simple block which contains an iframe, I would like a user to be able to close the iframe using a button.
Here is what I have so far
JS
UPDATE
document.querySelector(DOM.videoclosebtn).addEventListener('click', closeIframeContainer);
var closeIframeContainer =function(){
window.parent.postMessage("event=closeiframe", "*");
};
window.addEventListener("message", receiveMessageFromIframe, false);
function receiveMessageFromIframe(msg) {
if (event == "closeiframe") {
document.getElementById('iframe-container').remove();
}else{
alert('hehehe');
}
}
Here is index.html with iframe
<div id="iframe-container">
<iframe src="/videoexplainer/data.html" style="border:none"></iframe>
</div>
Here is data.html
<div id="video-close_btn" class="video-btn">
<img src="images/x.png" />
</div>
Error:
Uncaught TypeError: Cannot read property 'window' of null
at HTMLDivElement.closeIframeContainer (videoexplainer.js:123)
unfortunately its not working, what do I need to do get what I want?

Your code assigns the return value from the .postMessage() call to getIFrameID, but then you expect to use it as a DOM node reference.
var closeIframeContainer = function(){
var getIframeID = document.getElementById('iframe-container');
getIframeID.parent.postMessage("*");
getIframeID.style.display="none";
};
Get the element node reference first, and then do the other operations.

Related

jQuery throws an error that iframe.getElementById is not a function

Any function to target that same iframe object is not working and the following error is thrown:
Uncaught TypeError: target[0].getElementsById is not a function
I want to access the value of objects of an iframe
function fetchmap(target) {
console.log(target[0])
var el = target[0].getElementsByTagName('input #pac-input');
var e = target[0].getElementsById('pac-input')
console.log(el);
};
<div class="col-md-12 px-4 md-form form-group" id="placefinder">
<iframe id="iframe" src="//developers.google.com/my-business/content/tools/placeid-lookup" width="100%" height="400px" onload="fetchmap($(this))"></iframe>
</div>
It's getElementById (singular), not getElementsById (plural). It returns a single element.
Also note that the elements in a document inside the iframe are not descendants of the iframe itself. You have to use iframe.contentDocument.getElementById().

How to copy iframe content to div?

See code snippet below. I want the output text in the iframe to show in the #source div. Iā€™m struggeling with this, and am grateful for any ideas. How can I copy the output text in the iframe to a div?
(The script writes "Can see text!" in div #show if div #sourcediv contains "Text", else "Cannot see text!".)
<html>
<body>
<div id="source"></div>
<div id="show"></div>
<script>
if (document.getElementById('source').innerHTML.indexOf("Text") != -1)
{document.getElementById('show').innerHTML="Can see text!";}
else{document.getElementById('show').innerHTML="Cannot see text!";}
</script>
<iframe id="iframe" src="http://majaulrika.esy.es/text.txt">
</body>
</html>
Keeping in mind that your iframe is on the same domain as your page:
// Get your iframe element
var iframe = document.getElementById('iframe');
// Access contents of it like this
var iframeContent = iframe.contentWindow.document;
// Get your div element
var content = document.getElementById('source');
// set contents of this div to iframe's content
content.innerHTML = iframeContent.innerHTML;
Depending on when you're doing this, it also might be worth to wait till the iframe loads:
iframe.onload = function() { /* put the above code here */ }
Further your comment:
A better solution to get a content from file is to use ajax.
Here is a simple approach of using ajax with jQuery.
$.ajax({
url: 'http://output.jsbin.com/sebusu',
success: function(data) {
$('#source').html(data);
$('#show').text(function(){
if (data.indexOf('Text') != -1) {
return 'Can see text!';
}
else {
return "Can't see text!";
}
});
},
error: function(){
console.log(error);
}
});
<div id="source"></div>
<div id="show"></div>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
Live Demo
Again, you can call ajax only for your website (with some exceptions)
$("#my_iframe").on('load', function() {
$("#my_div").empty().append($('#my_iframe').contents().find('body').html());
});
Note: 'body' can be anything inside the iframe, if you want only a particular div, you can do '#div_inside_iframe' instead of 'body' using 'body' or 'html' will copy everything inside the iframe into the destination div.

How can I get url from java script ad line?

I have one div when I click that div I want to open a child browser.I have the code for child browser but when I click the div it executes the javascript line and I didn't get any url from there.
Please check my code
Div code
<div class="box_padding " onClick="window.open(this.href,'targetWindow','toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes);return false;" id="column-c-box-1" >
<script type="text/javascript" src="http://ad.leadboltads.net/show_app_ad.js?section_id=838333320"></script>
</div>
when I tried this nothing happening.
So I have tried one more way to solve this issue
function openwindow(){
w=open("myurl",'windowname','width=600,height=250,scrollbars,resizable,toolbar,status');
with(w.document){
write("<body>");
write("This is a new window");
write("</body>");
}
return false;
}
HTML:
<div class="box_padding "onClick="openwindow();" id="column-c-box-1" >
<script type="text/javascript" src="http://ad.leadboltads.net/show_app_ad.js?section_id=838333320"></script>
</div>
This is also not working.
If you have jquery available you can use this instead of this.href:
$('script').attr('src');
function openwindow(){
w=open($(this).find('script').attr('src'),'windowname','width=600,height=250,scrollbars,resizable,toolbar,status');
with(w.document){
write("<body>");
write("This is a new window");
write("</body>");
}
return false;
}
This seems to work in a preliminary test, native javascript. This would be trivial w/ jquery as a previous poster has shown.
Use the URL as a parameter in the div tag "srcVal".
<div class="box_padding " srcVal="http://ad.leadboltads.net/show_app_ad.js?section_id=838333320" onClick="openwindow()" id="column-c-box-1">click me</div>
or this way:
<div class="box_padding "onClick="openwindow();" id="column-c-box-1" >
<script type="text/javascript" src="http://ad.leadboltads.net/show_app_ad.js?section_id=838333320" id="scriptTag"></script>
</div>
Your function slightly modified:
function openwindow(){
var id = document.getElementById("column-c-box-1").getAttribute("srcVal");
//or
// var scr = document.getElementsByTagName('script');
//var id = scr[0].src; // use scr[scr - 1].src if have multiple scripts
var w=open(id,'windowname','width=600,height=250,scrollbars,resizable,toolbar,status');
with(w.document){
write("<body>");
write("This is a new window");
write("</body>");
}
return false;
}
I used "with" because that is in your original code, but I'd caution against it.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/with?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FStatements%2Fwith

Uncaught TypeError: Cannot read property 'innerHTML' of null functions.js:29 changeNameToLetters functions.js:29 onclick

Hi everybody I am getting this error in my console.
Uncaught TypeError: Cannot read property 'innerHTML' of null functions.js:29
changeNameToLetters functions.js:29
onclick
I tried searching for that but I am new to javascript and am not quite sure of how to fix it. Initially I had my script in the head tag and switched it to right before the ending body tag to see if it was an error with how everything was loading but unfortunately it still didn't work. I checked my spelling of my id and the text within my h3 tag and they seem fine to me. Like I said though I am very new to javascript and probably overlooking something obvious.
Thanks for your input!
Here is my html.
<body>
<h3 id"changeH3Text" onClick="changeNameToLetters()">
Regular Keyboard on Hover
</h3>
<div id="keyboardContainer" class="keyboard">......</div>
<script src="js/functions.js"></script>
</body>
Here is my javascript:
function changeNameToLetters(){
//keyboard container variables
var keyboardState= document.getElementById("keyboardContainer");
var currentClass = keyboardState.className;
//h3 text variables
var h3Text=document.getElementById("changeH3Text");
var currentText=h3Text.innerHTML;
if (currentClass == "keyboard_normal" && currentText =="Tool Name on Hover" ) {
keyboardState.className = "keyboard";
h3Text.innerHTML="Regular Keyboard on Hover";
} //end if
else {
keyboardState.className = "keyboard_normal";
h3Text.innerHTML="Tool Name on Hover";
} //end else
} //End function
Harry is right
<h3 id="changeH3Text" onClick="changeNameToLetters()">
id did not have the = after it.

Changing div in iframe using Jquery

I have a "Page A". In this page is an iframe which displays "Page B".
<iframe id="iframeD" src="https://trello.com" width="600" height="600">
<p>Your browser does not support iframes.</p>
</iframe>
<div id="cTitle">Hello</div>ā€‹
(See the following fiddle for a working example: http://jsfiddle.net/noscirre/yYkUN/)
"Page B" contains a div with id landingHeader. How can I create a jQuery call on "Page A" replace this div with another div (whose content is found on "Page A") with id cTitle?
$("iframe").contents().find("#dTitle").attr('id','cTitle').html($('#cTitle').html());
Assuming you're not violating the same origin policy,
1, Give your iframe an id - <iframe id="frm" src="javascript:undefined;"></iframe>ā€‹
2, Get the Window and HTMLDocument from the frame
var iWin = document.getElementById('frm').contentWindow,
iDoc = iWin.document;
3, Ceck for existance of jQuery in iframe
if( ! iWin.$ ){
var jq = iDoc.createElement('script');
jq.type = 'text/javascript';
jq.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js';
jq.onload = ready;
iDoc.head.appendChild(jq);
}else{
ready(); // the stuff you want to do
}
4, Do what you want with jQuery
function ready(){
var div = iWin['$']('#frm_div')[0]; // example from fiddle
div.textContent = 'bar';
}ā€‹
See this fiddle.
You can change so only if the iframe domain is same as the parent domain. If it is so then you can change it by accessing the iframe from the parent window using the contentWindow property.
Go and check this post Changing an element's ID with jQuery
$(this).attr("id","newId");
If you want to change just content then do this:
$("div#bTitle").html($("div#cTitle").html());
Try this:
$("#iFrame").contents().find("#dTitle").attr('id','cTitle');
I think the iFrame might be an issue unless both share the same parent DOM. However, regardless, just for fun, i kicked up this quick and simple jQuery plguin for ya that could help.
Plugin updated It makes more sense to return the replacment than the old element, thus changed
$(function() {
if (!$.replaceWith) {
$.extend({
replaceWith: function(ele, newEle) {
ele.each(function(i) { $(this).before(newEle).remove(); });
return newEle;
}
});
$.fn.extend({
replaceWith: function(newEle) { return $.replaceWith($(this), newEle); }
});
}
});
Simple USE
$("#someElementID").replaceWith($("#anotherElementID"));
// or
$.replaceWith($("#someElementID"), $("#anotherElementID"));
For Instance:
$("#dTitle").replaceWith($("#cTitle"));

Categories