Changing text inside an iframe with JS - javascript

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/

Related

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')

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.

Hide div when another div is empty

I know theres lots of answers on this problem, but I've read through all I can find but still cant get it to work.
I have a div which i need to be hidden if another div is empty, or just containing whitespace.
<div id="rt-main" class="mb12">
<div class="rt-grid-12">
<div class="rt-block component-block main-overlay-light">
<div id="rt-mainbody">
<div class="component-content">
<div class="blog-featured"></div>
( I want to hide div.mb12 when div blog-featured = ' ' )
My closest bet is this:
$(document).ready(function() {
str = $('div.section').text();
if($.trim(str) === "") {
$('div.section').hide();
}
});
But I get all sorts of errors in the console when trying.
Now I've got "TypeError: Cannot call method 'text' of null"
On the actual site (not included in the question), you have this:
jQuery.noConflict();
This makes it so that $ is no longer jquery. Most likely because one of the many other libraries you have included uses the $ name. You can simply change your code to use jQuery in place of $:
jQuery(document).ready(function() { ...
Alternatively, you can assign jQuery to a different variable name:
var $j = jQuery.noConflict();
$j(document).ready(function(){ ...
You want this -
jQuery(document).ready(function () {
var str = jQuery('div.blog-featured').text();
if (jQuery.trim(str) === "") {
jQuery('div.mb12').hide();
}
});
Demo ---> http://jsfiddle.net/PqXWJ/20/
Are you loading the jQuery library before your script? Do you have something like this in the <head> tags of your page?
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
<script type="text/javascript">
$(document).ready(function() {
etc etc
</script>

Finding elements in an object that started as a string

I've got a textarea:
<p>
Input:<br>
<textarea name="text_input" id="text_input"></textarea>
</p>
I'm trying to treat the textarea value as a jQuery object to be able to find each hypertext link.
That textarea has some related script code:
<script>
$('#text_input').change(process).keyup(process);
function process(){
var html = $('#text_input').val();
$(html).find("a").each(function(i,elem){
alert('got here');
});
}
</script>
In that textarea, I paste, for example, the text:
<html>
<body>
hello
</body>
</html>
Problem is, the alert() never fires. What am I missing? I guess the $(html) line has issues.
Change $(html).find... into $('<div/>').append(html).find... and it will work.
http://jsfiddle.net/NQKuD/
If you want to treat the text as a complete HTML document, you'll have to parse it yourself rather than get jQuery to do it for you. Here's one approach:
function process() {
var html = $('#text_input').val();
var rgx = /<a [^>]*href\=\"?([^\"]+)\"?[^>]*>([^<]*)<\/a>/gi;
var result,url,link;
while (result = rgx.exec(html)) {
url = result[1];
link = result[2];
alert('url='+url+'\nlink='+link);
}
}
http://jsfiddle.net/NQKuD/2/
var html = $('#text_input').val(); <-- that is wrong
use var html = $('#text_input').html(); instead.
test code:
<textarea id="t123">text<something more</textarea>
<script>
window.alert($("#t123").val());
window.alert($("#t123").html());
</script>
also pay real close attention to what you get in the alert.
update:
okay, so difference would be that .html() would refer to the original content of the text area, where as val() would use with value entered/changed.
so, this would fix the problem:
$(document).ready(function(){
$('#text_input').change(function(){
var html = $('#text_input').val();
var dummy = $("<div></div>").html(html);
dummy.find("a").each(function(i, elem){
window.alert(elem);
});
});
});
You can create an invisible html placeholder and insert the html there (this sounds like a very dangerous method though, :P but I see no other way to use jquery to parse input text).
http://jsfiddle.net/y6tt7/1
<div id="placeholder" style="display:none"></div>
$("#placeholder").html(html).find("a").each(function(i,elem){
alert('got here 2');
}).html("");
If you are having trouble firing the event when pasting using "Paste" in the OS menu, try the input event:
$('#text_input').bind('input', process);
Also, to be able to parse the input content using jquery, you should probably append it to a DOM node:
$('#text_input').bind('input', process);
function process(){
var html = $('#text_input').val();
$('<div>').html(html).find('a').each(function(i, elem) {
alert('got here');
});
}
Example: http://jsfiddle.net/5npGM/9/
jQuery will strip out the html and body elements from your HTML string, the find function will then fail to find any a elements as it is searching inside a single a element.
See this question - Using jQuery to search a string of HTML
To prove the point, the following JavaScript will work if you put it inside a document ready block -
$('#text_input').change(process).keyup(process);
function process() {
var html = $('#text_input').val();
$('<div>' + html + '</div>').find("a").each(function(i, elem) {
alert('got here');
});
}
Demo - http://jsfiddle.net/Y5L98/4/

how to get tinyMCE editable for a cloned textarea by cloneNode(true) function

When I try to clone a textarea by using cloneNote(true), the cloned textarea is not editable. Does anyone know how to resolve the problem? The sample codes show as following:
<html>
<head>
<script type="text/javascript" src="/javascripts/tiny_mce/tiny_mce.js"></script>
<script type="text/javascript">
tinyMCE.init({
theme : "advanced",
mode : "textareas",
});
</script>
<script type="text/javascript">
testclonenode = {
addAbove : function (element) {
var rowEl = element.parentNode.parentNode.parentNode;
var rowElClone = rowEl.cloneNode(true);
rowEl.parentNode.insertBefore(rowElClone, rowEl);
return false;
}
};
</script>
</head>
<body>
<table>
<tr><td>
<textarea name="content" style="width:100%">this is a test </textarea>
<p> <button onclick='return testclonenode.addAbove.call(testclonenode, this);'> Add above </button>
</td></tr>
</table>
</body></html>
It does not work that way. Also, it is impossible to move a tinymce editor using dom manipulation.
The tinymce wiki states the following:
mceAddControl
Converts the specified textarea or div
into an editor instance having the
specified ID.
Example:
tinyMCE.execCommand('mceAddControl',false,'mydiv');
So when you clone a textarea there is another problem: You will have the same id twice which will result in errors accessing the right tinymce instance.
I got this to work by using an ID which is incremented each time my clone function is triggered, so
var insertslideID = 0;
function slideclone() {
$('<div class="slides"><textarea name="newslide['+insertslideID+'][slide_desc]" id="mydiv'+insertslideID+'"></textarea></div>').insertAfter('div.slides:last');
tinyMCE.execCommand('mceAddControl',false,'mydiv'+insertslideID);
insertslideID++;
}
$('input[name=addaslidebtn]').click(slideclone);
Seems to work.
A wee bit tidier, I just use a number for my id - copy1 is the name of my button - I add the new element to the end of my container.
var count = 0;
$("#copy1").click(function(){
var newId = count;
$( "#first" ).clone().appendTo( "#container" ).prop({ id: newId, });
tinyMCE.execCommand('mceAddControl',false,newId);
count++;
});
I ran into a similar problem, except my element IDs (not just textareas) could be anything, and the same ID was always appearing twice. What I did is supposed to be horribly inefficient but there was no noticeable performance loss with dozens of elements on the page.
Basically I removed the TinyMCE ID first (uses jQuery):
$(new_element).find('.mce-content-body').each(function () {
$(this).removeAttr('id');
});
Then I reinitialized TinyMCE for all relevant elements.

Categories