How to copy iframe content to div? - javascript

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.

Related

how to close Iframe using paremt post message in 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.

Replace a <div> with another html page with .innerHTML?

I am currently working on a project which allows for different webpages to be loaded into a <div> in my page when certain links leading to them are clicked , I have read up on the thread below but I do not have any idea on how to do jquery and I was wondering if the pages can be loaded with .innerHTML ? Are there ways to do it with only css and javascript and html?
Replace <div> with another HTML page
Basically what I want is something like w3.includeHTML() in which the entire page loads and show itself not within a frame but as part of the page
Here is a link to my project file and the main html page being used is index.html and the html page to linked to is greatwallofchina.html:
https://drive.google.com/file/d/1yAWZIIhBKHjwkiwwNhXUsQEVVQdjTxrM/view?usp=sharing
If you want to show another html inside another use the object element and you can use innerHTML to achieve this. Below are 2 functions for each link one will load one page and the other will load the second. The other option requires you to post your stylesheet
Hope it helps. The update to this Solution is to remove the extra scrollbar.
<script type="text/javascript">
function nextpage(){
document.getElementById('pageContent').innerHTML = "<object style=\"overflow:hidden; width: 99.25%; height: 101%\" width=\"100%\" height=\"101%\" data=\"http://localhost/test/page1.php\"></object>" ;
}
function nextpageb(){
document.getElementById('pageContent').innerHTML = "<object style=\"overflow:hidden; width: 99.25%; height: 101%\" width=\"100%\" height=\"101%\" data=\"http://localhost/test/page2.php\"></object>" ;
}
</script>
</head>
<body style="float:left; overflow:hidden; width: 100%; height: 101%">
<nav>
<h2 class="hidden">Our navigation</h2>
<ul>
<li><a onclick="nextpage();">Home</a></li>
<li><a onclick="nextpageb();">Contact</a></li>
</ul>
</nav>
<div id="pageContent">Hello motto </div>
Do this:
not sure of the format of these "links" if you have access to them then you can use one of a couple of ways
use the HTML and any variant of the following Javascripts (JS)
HTML
<iframe id="myFrameID" src="" width="0px" height="0px" style="display:hidden;visibility: hidden"></iframe>
<div id="myPageViewerDIV"></div>
JS with selectors
$('a[href="formatoflinkhere"]').click(function () {
$("#myFrameID").attr("src", $("a:focus").attr("href"));
$("#myFrameID").bind('load', function() { $("#myPageViewerDIV").html($("#myFrameID").contentDocument); });
return false;
});
JS with any links
$('a').click(function () {
$("#myFrameID").attr("src", $("a:focus").attr("href"));
$("#myFrameID").bind('load', function() { $("#myPageViewerDIV").html($("#myFrameID").contentDocument); });
return false;
});
JS with any links but ids (the hash symbol)
$('a[href!=#]').click(function () {
$("#myFrameID").attr("src", $("a:focus").attr("href"));
$("#myFrameID").bind('load', function() { $("#myPageViewerDIV").html($("#myFrameID").contentDocument); });
return false;
});
you or other users can add on to this ^^/'
what this does:
Creates a hidden invisible IFrame
Binds All Links (or variant type) with the onclick event handler
(returns false so no browsing to the link
load the link into the source
binds to the onloaded event of the iframe
copys the iframe's root document to the dive of your choices...
TL;DR
Not tested, should work in theory.
You can try loading the page in your div as given below
USING JAVASCRIPT::
<div id="result">
</div>
<script type="text/javascript">
function myFunction() {
document.getElementById("result").innerHTML = '<object type="text/html" data="/path/of/htmlpage.html" ></object>';
}
<script>
USING JQUERY ::
$(document).ready( function() {
$("#yourLinkId").on("click", function() {
$("#YourDiv").load("../pages/PageYouWantToShow.html");
});
});
$(document).ready( function() {
$("#yourLinkId").on("click", function() {
$("#YourDiv").load("../pages/PageYouWantToShow.html");
});
});
functionyouFunc(){
document.getElementById("element").innerHTML='<object type="text/html" data="/statics/health.html"</object>'
}
Its simple - Just call a javascript function on clicking the link and load your html as follows
$("#divid").load('path of file')

Changing text inside an iframe with JS

I have an HTML page which loads some content in an iframe with the help of remote JS. I want to replace the text "premium content" with something else.
What I am trying is:
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript" src="http://gaand.comli.com/no.js"></script>
<img src="psss" onerror="myFunction()"></img>
<script>
function myFunction() {
var x = document.getElementById("overlay_iframe");
var y = x.contentDocument;
y.document.body.innerHTML = y.document.body.innerHTML.replace('premium',
'newtext');
}
</script>
</body>
</html>
Is there any way to change it as soon as the page is loaded completely?
You can use jquery to have event when page loads, and then replace html content.
$( document ).ready(function() {
$( "#overlay_iframe" ).html( $( "#overlay_iframe" ).html().replace("premium","newtext"));
});
Unless the iFrame is on your server you cannot change it. I would suggest using PHP
file_get_contents()
and replacing it within the string.
You can try using the jQuery .contents() to return an object of the iframes contents and than manipulate that. jQuery .contents()
Edit, updated
Try
$.getScript("http://gaand.comli.com/no.js")
.done(function(script) {
s = setInterval(function() {
$("iframe").contents()
.find("body").text(function(_, o) {
return o.replace("premium", "newText");
}) && clearInterval(s);
}, 10);
});
jsfiddle http://jsfiddle.net/guest271314/whjqqtco/

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

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