load a document string into an iframe - javascript

I have a string (fetched via ajax), which is an entire html document (doctype to < /html>). Does anyone know of a way to load it into an iframe?
I cannot simply specify the url that returned the document in the src of the iframe, since the response may have come from a post, and repeating it may have ill effects. Also, I can't submit it to the iframe the first time, since I can't predict absolutely that the result will be a document and not some json. Basically, I can't recall the url, I must be able to use the version I have (a string).
jQuery is fair game, since that's what I'm using.

You can do this using a data URI. A data URI is a way to load inline data as if you're loading external data. They look like this: data:<mimetype>,<data>. For HTML, the mimetype is text/html, and in your case, the data is something like this: <!DOCTYPE><html><head><title>Iframe</title></head><body>Hi!</body></html>. If we put this in a data URI, we get something like the following:
data:text/html,<!DOCTYPE><html><head><title>Iframe</title></head><body>Hi!</body></html>
When we set this as the src of the iframe, it looks like this.
var string = '<!DOCTYPE><html><head><title>Iframe</title></head><body>Hi!</body></html>',
iframe = $('#iframe')
iframe.attr('src', 'data:text/html,' + string)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<iframe id="iframe" src=""></iframe>

#LarsW one doesn't need to use jQuery. For example, if the html string is a file that resides in the filesystem but it is not accessible from www (or you have to construct it in PHP), you can use this PHP code
$htmlText = "data:text/html;base64,".base64_encode(file_get_contents("someFolder/file.html"));
echo "<iframe src='$htmlText'></iframe>";
I've had problems without base64 extension because quotes in file.html can break the HTML code.

Related

I want to take url from page's view page source

For example this url
https://in.pinterest.com/pin/695524736192250687/
from its page source want to take
<img alt=" " class="hCL kVc L4E MIw" importance="auto" loading="auto" src="https://i.pinimg.com/236x/a8/7f/22/a87f2200109b01fc7a74b6106cb76f7b.jpg"/>
echo this from its page source:
https://i.pinimg.com/236x/a8/7f/22/a87f2200109b01fc7a74b6106cb76f7b.jpg
on
https://youtubethumbnaildownload.online
You can use SimpleHtmlDom to scrape the data from the source code and then look for the class and img tags or whatever else you need to do.
A simple PHP HTML DOM parser written in PHP5+, supports invalid HTML, and provides a very easy way to find, extract and modify the HTML elements of the dom. jquery like syntax allow sophisticated finding methods for locating the elements you care about.
You can store this url into session variable for the current page and then retrieve this session on another page where you want that url.
like :
$_SESSION['url'] = $url; // store value/url in session
$uel= $_SESSION['url']; //retrieve session value on another page
Make sure that you need to strat your session first.
session_start();

Insert HTML Content from URL into HTML (form, div, iframe, ...)

I want to display the result of this URL
http://api.openweathermap.org/data/2.5/weather?q=Berlin,de&mode=html&appid=...1
which looks like
https://i.stack.imgur.com/WWRoD.png
how can I insert the HTML content from the URL directly into an iframe or div?
Thanks!
If you already are able to get that response html, all you need to do is insert it onto the page
document.getElementById('mydiv').innerHTML = "<p>some html</p>"
This could easily be achieved by PHP.
<?php
echo file_get_contents("ENTER URL HERE");
?>
You could do this via JavaScript, but that would require making an AJAX request to get the HTML and then inserting it into the DOM. I don't think that this would be the best method as the page would have already loaded without the code and then asynchronously adding it to the page. Depending on how it is meant to be viewed, I think this would lead to a poorer UX.
Edit
To download the HTML asynchronously, you should use .get(), instead of .load().
$.get("URL", function(data) {
$(".mydiv").html(data);
});

Parse a HTML String with JS without triggering any page loads?

As this answer indicates, a good way to parse HTML in JavaScript is to simply re-use the browser's HTML-parsing capabilities like so:
var el = document.createElement( 'html' );
el.innerHTML = "<html><head><title>titleTest</title></head><body><a href='test0'>test01</a><a href='test1'>test02</a><a href='test2'>test03</a></body></html>";
// process 'el' as desired
However, this triggers loading extra pages for certain HTML strings, for example:
var foo = document.createElement('div')
foo.innerHTML = '<img src="http://example.com/img.png">';
As soon as this example is run, the browser attempts to load the page:
How might I process HTML from JavaScript without this behavior?
I don't know if there is a perfect solution for this, but since this is merely for processing, you can before assigning innerHTMl replace all src attributes to be notSrc="xyz.com", this way it wont be loaded, and if you need them later in processing you can account for this.
The browser mainly will load images, scripts, and css files, this will fix the first 2, the css can be done by replacing the href attribute.
If you want to parse HTML response without loading any unnecessary resources like images or scripts inside, use DOMImplementation’s createHTMLDocument() to create new document which is not connected to the current one parsed by the browser and behaves as well as normal document.

refreshing javascript by renaming src attribute

I want to refresh the output of the script below. Is this json? Do I need to add a crossdomain policy in my site?
<div id="nowplaying">
<script src="http://s4.total-streaming.com/xml.php?station=1269&get=js"></script>
</div>
Edit:
This is what I'm trying based on #alexn advise, but still doesn't refresh.
<div id="nowplaying">
<script id="nowplaying-script" src="http://s4.total-streaming.com/xml.php?station=1269&get=js"></script>
<script>
setInterval(function () {
$('#nowplaying-script').attr('src', 'http://s4.total-streaming.com/xml.php?station=1269&get=js');
}, 1000);
</script>
</div>
Note Firebug: Resource interpreted as script but transferred with MIME type text/html. xml.php:-1
No, it's plain JavaScript. The script will simply output a string. You don't need any cross-domain policies to use this.
To refresh the content, just re-assign the src attribute of your script tag to the same url. You can use setTimeout to do this on a specified interval. Something like this should do it, you need to ad an id attribute to your script tag. The following will refresh every 5:th second.
setInterval(function() {
var element = document.getElementById("nowplaying-script");
element.setAttribute("src", "http://s4.total-streaming.com/xml.php?station=1269&get=js");
}, 5000);
(This is untested)
I would lean towards this being a cache problem.
How about you try this plugin (or look into how it works): http://plugins.jquery.com/project/reload
It essentially would allow you to do this:
setInterval(function () {
$('#nowplaying-script').reload();
}, 1000);
If you don't want to use the plugin, all it's doing is appending the current date to the URI params.
Another thing I noticed is that the script you are loading contains document.write. Even if you managed to get it to reload, it's not going to do what your expecting it to do.
In fact, calling document.write on a already loaded HTML page will cause your page to turn blank and contain only the content passed to document.write.
Now I'm not sure if your script is running on the same hostname as the script you are loading, if isn't you going to need a JSONP API instead of an a script that writes into the page.
If they do not offer a JSONP API, a more hackish way to solve this problem would be to write a server-side script that acts as a proxy. It essentially would load http://s4.total-streaming.com/xml.php?station=1269&get=js, parse it server-side using a substr or RegEx and return back the text that you want, in this case the name of the song currently playing.
Another way to solve this problem would be to overwrite the document.write method and have it print the content into the div instead of onto the screen like this:
document.write = function(songName) {
$('#nowplaying').text(songName);
};
Personally I wouldn't use this solution, but it will work if the other solutions are too complex for you to setup. Keep in mind all calls to document.write on that given page will print the content into your #nowplaying element. You should probably move your SCRIPT tag out of the #nowplaying element too if you use the above solution.

Getting content of a script file using Javascript

I have the following script element in my web page:
<script src="default.js" type="text/javascript"></script>
Using JavaScript, I want to be able to retrieve the content of the script file. I know I could use an ajax request to get the data but then I am getting something from the server that I already have locally.
So what I would prefer to do is retrieve the content from the DOM (if that's possible) or something that has the same result.
Cheers
Anthony
UPDATE
I was trying to simplify the question, maybe a bad a idea, I thought this way would cause less questions.
The real situation I have is as follows, I actually have
<script type="text/html" class="jq-ItemTemplate_Approval">
...
html template that is going to be consumed by jQuery and jTemplate
...
</script>
Now this works fine but it means each time the page loads I have to send down the template as part of the HTML of the main page. So my plan was to do the following:
<script src="template.html" type="text/html"></script>
This would mean that the browser would cache the content of template.html and I would not have to send it down each time. But to do this I need to be able to get the content from the file.
Also in this case, as far as I know, requesting the content via ajax isn't going to help all that much because it has to go back to the server to get the content anyway.
If I understand you correctly, you don't want to use Ajax to load an html template text, but rather have it loaded with the rest of the page. If you control the server side, you can always include the template text in an invisible div tag that you then reference from Javascript:
<div id="template" style="display:none;">
...template text...
</div>
<script>
// pops up the template text.
alert(document.getElementById("template").innerHTML);
</script>
If you are just looking for to load the template so that you can have it cached, you can put the contents in a variable like this:
<script>
var template = "template text..";
</script>
or you can load it using ajax and store the template in a variable so it is accessible. It's pretty trivial in jquery:
var template;
$.get("template.html", function(data){
template = data;
});
unless you load a script as literal text in the page, it does not exist as text. It is interpreted by the browser and melded into the runtime, with any other scripts.
If you want the source you have to fetch it again,if with Ajax get the responseText.
It will come from the browser cache, and doesn't have to be downloaded again.
I think what you want to do is to assign a variable inside template.js. Then you have the variable available for use wherever you want in jquery. Something like:
var tpl = "<div> ... </div>"
Wouldn't this be a simpler solution to your problem? We do this in Ext JS. I think this will work for you in jQuery.
You could get the attribute of the src of the script and then use XHR to get the contents of the JS file. It's a much cleaner way of doing it IMO. e.g.:-
if(window.XMLHttpRequest) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if(xhr.status == 200 && xhr.readyState == 4) {
var sourceCode = xhr.responseText;
alert('The source code is:-\n'+sourceCode);
}
}
xhr.open("GET",document.getElementById('scriptID').src,true);
xhr.send(null);
}
Using an iFrame & HTML5 Local Storage
Save the templates for rendering later...
not stoked about the iFrame, but it seems to be working pretty good (haven't ran performance tests yet)
Put the iFrame on the page you want the template on (index.html)
<html>
<head>
<iframe src="mustache.Users.html" onload="this.remove();" class="hidden" id="users_template"></iframe>
</head>
</html>
Make sure the src attribute is set
hide the element until you can get rid of it after it loads
Put this body wrapper around your template (mustache.Users.html)
(don't worry it won't show up in the template)
<body onload="localStorage.setItem('users_template',this.document.body.innerHTML);">
<ul class="list-group" id="users" >
{{#users}}<li>{{name}}</li>{{/users}}
</ul>
</body>
replace 'users_template' with whatever name for your variable
the 'onload' attribute saves the template into localStorage during load
Now You can access your templates from anywhere
localStorage.getItem('users_template')
OR
window.localStorage.getItem('users_template')
What is in the JavaScript file? If it's actual code, you can run functions and reference variables in there just like you had cut and paste them into the webpage. You'll want to put the include line above any script blocks that reference it.
Is this what your looking to accomplish?
Why not use Ajax (well Ajah because its html :-))?
when the server is set up correctly and no no-cache or past expires headers are sent, the browser will cache it.
The way that most JavaScript import files work is they include a script, that immediately calls a function with a parameter of certain text, or of another function. To better illustrate, say you have your main index.html file, set it up like this:
<html>
<head>
</head>
<body>
<script>
let modules = {};
function started(moduleName, srcTxt) {
modules[moduleName] = (srcTxt) //or something similar
}
</script>
<!--now you can include other script tags, and any script tags that will be included, their source can be gotten (if set up right, see later)-->
<script src="someOtherFile.js"></script>
</body>
</html>
now make that other file, someOtherFile.js, and right away when its loaded, simply call that "started" function which should already be declared in the scope, and when thats done, then whatever text is passed, from the file, is stored in the main index.html file. You can even stringify an entire function and put it in, for example:
started("superModule", (function() {
/*
<?myCustomTemplateLanguage
<div>
{something}Entire Javascript / html template file goes here!!{/something}
</div>
?>
*/
}).toString());
now you can access the inner content of the function, and get all the text in between the comments, or better yet, then do other parsing etc, or make some other kind of parsing identifiers at the beginning and end of the comments, as shown above, and get all text in between those

Categories

Resources