How to get javascript to load another html file? - javascript

I am trying to create a bookmarklet, so that when you click on it, it will load example.com/yourdata.php in a div box.
How can I make it get the data from example.com?
IFRAME? or is there a better solution?

You may have issues with creating a bookmarklet within another page that grabs data from a different domain (to load into a <div /> using Ajax).
Your best option is probably to insert an IFrame with the content as the source of the page.
If you want to do this as a very basic lightbox, you could do something like this:
(function() {
var iFrame = document.createElement('IFRAME');
iFrame.src = 'http://google.com';
iFrame.style.cssText = 'display: block; position:absolute; '
+ 'top: 10%; left: 25%; width: 50%; height: 50%';
document.body.insertBefore(iFrame, document.body.firstChild);
})();
And here is the same code in bookmarklet format:
javascript: (function() { var iFrame = document.createElement('IFRAME'); iFrame.src = 'http://google.com'; iFrame.style.cssText = 'display: block; position:absolute; top: 10%; left: 25%; width: 50%; height: 50%'; document.body.insertBefore(iFrame, document.body.firstChild); })();
You could also style this a lot more if you wanted something pretty. This is just a basic example of what is possible. As another person said, it would be easiest to make it pretty by loading jQuery using an Ajax request, but that is a little more involved.

Do an AJAX call directly in your bookmarklet, and then set the innerHTML of your div to the returned content. Not sure if there are security restrictions on this or not.
Edit: You don't want to use JQuery, as you can't easily load a javascript library from a bookmarklet. (Although maybe you could get it via AJAX and then eval it...)
You need to do a classic XMLHttpRequest.
Some more info here.

With The Dojo Toolkit you can use dijit.layout.ContentPane or dojox.layout.ContentPane to do exactly what you want in one single div.
The difference between dijit.layout.ContentPane and dojox.layout.ContentPane is that you can run inline javascript inside the dojox.layout.ContentPane.

I got around the domain restriction by making a php function on my server that outputs a page on another domain. that way, javascript thinks it is in the same domain when I do an ajax.updater call.
$sSrcPage = $_REQUEST['SrcPage'];
echo file_get_contents($sSrcPage, 0);

Related

Create an overall header(how to)

I know this question won't be well received but I searched far and long and can't find anything, probably not using the right keywords.
I own an online radio station and I want to create a js player that once added to a website will stay in the header on all the domains of the site. I first saw this thing on a tumblr music player(http://scmplayer.net/) , you would add their code to your page and once opened the player will stay as a header even if you browse to other sub-pages of your blog.
I'm searching for this to use in forums, where you change your page so often you can't listen to anything using a built-in radio player.
I found a similar solution by using a button that opens a really small pop-up with the player, but I'd like to know if it's possible to do what I want, and how.
Even a right link, query or term to search for would help me greatly, I don't want someone to do this for me, just point me in the right way.
Edit::
Here's some stuff I forgot to mention. I'm trying to build a code users can just copy paste into their website and have it work.
If it was only for me, I wouldn't be here, since I went trough iframes and jquery to load content too(see www.r4ge.ro).
I can't expect other people to tamper with their website only to embed my radio there, and I can't iframe their site content and add my radio as an index because that would ruin google ranking and indexing.
There are multiple ways of doing this, here goes one!
First thing, I'd personally use backbone.js - backbone.js allows you to create 'partial' views that can be updated independently of another. For your scenario, it seems ideal to create a header view and then a content view.
Both the header and the content could have their own logic, and update at separate times that you specify and under your control.
Take a look at http://backbonetutorials.com/why-would-you-use-backbone/ to get started. prepare yourself ample time to do a lot of reading and following tutorials. Backbone takes time to ramp up on, but once you get it, you'll be making some awesome apps!
You basically have three options:
The one you found, opening a really small pop-up (perhaps with just the media controls visible), so that when the user navigates, it isn't affected by the page being torn down.
The same thing using frames.
The same thing using ajax to load content when navigating instead of actually navigating.
As you didn't like #1 much, let's look at #2, then come back to #3.
When the use opens the player, you'd really be going to a page with the player and a very large iframe with the rest of the content:
<!doctype html>
<html>
<head>
<!-- ... -->
</head>
<body>
<!-- player here -->
<iframe class="main" src="main.html"></iframe>
</body>
</html>
You'd use CSS to make that as seamless as you could. To make it linkable, you could use a large fragment in the URL which is the URL of the page that should go in the frame, e.g.:
http://example.com/#forum.html&section=23
When your main page loads, you grab the fragment, and use it as the src on the iframe.
You can listen for navigation events on the iframe and update the hash fragment on the main window, so that bookmarks work, and/or have JavaScript on each page of your site that might be navigated to that tells the container page (parent) what its URL is.
#3 is similar to #2 except that rather than letting navigation happen the normal way, you load everything via ajax as the user clicks around, loading it into (say) a main content div rather than an iframe. This can also use hash fragments to ensure that it's fully linkable/bookmarkable, etc., but requires that all links in the pages loaded get rewritten so they update the hash fragment rather than the main URL instead.
#2 and #3 (and #1) all have their advantages and disadvantages. #1 is probably the least work. #2 probably comes in second, then #3, but I could have those backward.
Here's a quick and dirty version of #2 that polls for hash updates so that the pages loaded in the frame don't have to know anything about this at all. Note that all you'd have to give to the other people is the page; their pages remain the same. If they're concerned about page rank, they'll want to include the canonical URL of their pages in the markup.
withplayer.html:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Example</title>
<style>
html, body {
padding: 0;
margin: 0;
}
html {
height: 100%;
box-sizing: border-box;
}
*, *:before, *:after {
box-sizing: inherit;
}
body {
height: 100%;
position: relative;
}
div.player {
height: 30px;
padding: 2px;
}
iframe.content {
border: none;
position: absolute;
top:30px;
width: 100%;
/*bottom: 0px; Sigh, this works on elements other than iframe, see 'resize' JavaScript below */
}
</style>
</head>
<body>
<div class="player"></div>
<iframe class="content"></iframe>
<script>
(function() {
// Fill in our "player"
var dt = new Date().toISOString();
document.querySelector(".player").innerHTML =
"This div is our pretend player: The div was loaded on " +
dt.substring(0, 10) + " at " + dt.substring(11, 19) + ".";
// Get the iframe
var content = document.querySelector(".content");
// Listen for hash changes
window.onhashchange = loadContent;
// Load any initial hash we have
loadContent();
// Get our current hash, without the leading #
function getHash() {
return location.hash.replace(/^#/, '');
}
// Get the hash equivalent of the current content in the content iframe
function getContentHash() {
var loc, hash;
loc = content && content.contentWindow && content.contentWindow.location;
hash = loc && loc != "about:blank" ? loc.pathname + loc.search + loc.hash : undefined;
return hash;
}
// Load the content for the current hash
function loadContent() {
// If we have an initial hash, apply to the iframe
var hash = getHash();
if (hash) {
content.src = hash;
}
}
// Poll for changes to the frame's location, update our hash if
// it doesn't match
setInterval(pollContent, 100);
function pollContent() {
var newHash;
newHash = getContentHash();
if (newHash !== undefined && newHash !== getHash()) {
location.hash = "#" + newHash;
}
}
// Stoopid iframes won't stick to the bottom, have to resize their height
resize();
window.onresize = resize;
function resize() {
content.style.height = (window.innerHeight - 30) + "px";
}
})();
</script>
</body>
</html>

iPad: How to print a pdf in an iframe in javascript

Using javascript -- in an iPad html5 web app, is it possible to print a pdf which is loaded in an iframe?
I have tried numerous things without success such as:
var iframe = document.getElementsByTagName('iframe')[0]
if (iframe.attachEvent) {
iframe.attachEvent("onload", function(){
console.log("Local iframe is now loaded.");
iframe.contentWindow.print()
});
}
else {
iframe.onload = function(){
console.log("sLocal iframe is now loaded.");
iframe.contentWindow.print()
};
}
The iframe's url is '/data/xyz.pdf';
The goal is for the airprint dialog to open. This is a major issue for me, please help!!!
I think you are nearly get the solution. The only left is just how you print the iframe. Try to use this.
window.frames["iframe"].focus();
window.frames["iframe"].print();
Hope it helps
:)
A different way to the other two answers is to use CSS to print only the iframe:
#media print {
* {
display: none;
}
iframe {
display: block;
width: 100%;
height: 100%;
}
}
This basically makes the iframe the full width and height of the page, and hides other elements, so that the iframe is the only thing in view when the user clicks print. The advantage over the other options is that it will work with JavaScript turned off, which some users may have done for security reasons.
I'm pretty confident about safari supporting PDFObject. It's just an object to declare, pretty easy to use.
Even if not exactly an iframe, you can use a div this way :
<div id="pdfIframe"></div>
var pdf = new PDFObject({
url: "/data/xyz.pdf",
id: "pdfRendered",
pdfOpenParams: {
view: "FitH"
}
}).embed("pdfIframe");
Source : http://pdfobject.com/
EDIT : I did not see it was a printing issue, so my answer isn't really one. BTW, i remember a friend using it, he had no problem to print it, so maybe there is an included printing support function.

Make a call to a custom protocol in Javascript

I'm running a script in a UIWebView which sends data back to the host application (in Objective-C). If I put a link on the page pointing to myprotocol://some_data, I receive the information on the host side.
How can I achieve the same behaviour in pure Javascript, without user interaction? Something like a AJAX call, but not over HTTP?
I'm using AngularJS, but any solution in Javascript is welcome.
I found that there was no way to do this without "cheating" in some way. I decided to create a <a> element in my page and dynamically change its href attribute, then triggering the click event on it with Javascript. Here is what I did :
CSS
a#sendToiOS {
display:block;
position: fixed;
bottom: -1px;
right: -1px;
z-index: -1;
opacity: 0;
width: 1px;
height: 1px;
}
Javascript
var sendToiOS = function(protocol, action, params) {
var e = document.createElement('a');
e.id = 'sendToiOS';
var strParams = "";
if(typeof params !== 'undefined') {
Object.keys(params).forEach(function(key) {
strParams += strParams != "" ? '&' : '';
strParams += key+'='+encodeURI(params[key]);
});
}
e.href = strParams.length > 0 ? protocol+'://'+action+'?'+strParams : protocol+'://'+action;
document.getElementsByTagName('body')[0].appendChild(e);
e.click();
e.parentNode.removeChild(e);
}
Calling sendToiOS('mycustomprotocol', 'some_action', {foo: 'bar', foo2: 1337}); would then trigger a call to mycustomprotocol://some_action?foo=bar&foo2=1337.
OK, I dug around inside the guts of Cordova and it seems like they use an iframe bridge for this. Essentially they dynamically create an iframe (so the iframe domain is the same as the calling page), then update the iframe src to a custom protocol URL.
Interestingly the iframe bridge is a fallback mode for iOS4; they do use an XMLHttpRequest, but I'm not yet certain how they work around the same-domain policy.
EDIT: To do this they register a custom NSURLProtocol, and then issue a HEAD request along with the desired data.
If you want to take a closer look, search for the exec.js file inside the cordova-js.zip file which comes with Cordova. You can find the custom protocol as CDVURLProtocol.m inside cordova-ios.zip.

Show loading while document is not ready

I want to show the user that the document which he wants to access
is loading and not ready yet.
I want to show the web-page when it is fully loaded.
I use
$(document).ready(function(){});
for document ready. What should I do for my approach?
The first thing to do is ask why the page is so slow to load that you feel you need a loading banner, and to do whatever you can to fix that.
If you can't fix that because of the nature of the page in question, the next consideration is making sure that the "Loading" banner only appears for people who have JavaScript enabled (because we're going to remove it later with JavaScript, so it would be a bit mean to put it there and then not remove it if they don't have JavaScript). This may be one of the few valid remaining uses of the document.write statement (and only if you're not using XHTML, because it's not valid in XHTML):
<body>
<script>
document.write("<p id='loading'>Loading...</p>");
</script>
...which you'd style with CSS, presumably:
#loading {
position: absolute;
left: 0px;
top: 0px;
background-color: #ddd;
/* ... */
}
And then in your ready handler, remove it:
$('#loading').remove();
If you're using XHTML (or you just don't want to use document.write on principle), you can do something similar without document.write, along the lines of:
<body>
<script>
(function() {
var p = document.createElement('p');
p.id = 'loading';
p.innerHTML = "Loading...";
document.body.appendChild(p);
})();
</script>
Live example (Tested on IE6/7/8 on Windows; Safari on Windows; and Chrome, Opera, and Firefox on Linux and Windows.)
Write some element with the loading text/animation at the start of the code, then remove or hide that element with javascript on document ready. Some output buffering might be needed to get the loading-message to show up right away.
$(function() {
$("#loading_element").hide();
});

How to display iframe by a Javascript snippet?

I have seen some widgets online that gives the user the possibility of including a short Javascript snippet in their own page, which when executed displays an Iframe, like in the following example.
<div id="fb-root"></div><script src="http://connect.facebook.net/en_US/all.js#appId=APP_ID&xfbml=1"></script><fb:facepile></fb:facepile>
How can I do this by myself - have a javascript on my server, that when called on a remote server, writes out an iframe or loads content into their page?
The traditional way (considered a bit messy; won't work with XHTML-as-XML host pages; if called after page load via async, will blow up the entire page):
document.write('<iframe src="http://www.example.com/myframe" width="100" height="100"></iframe>');
Alternatively with innerHTML to an element on the page with a predefined name:
document.getElementById('examplecomframe').innerHTML= '<iframe src="http://www.example.com/myframe" width="100" height="100"></iframe>';
Or with DOM to insert just before the current <script> (though again that can be unpredictable if deferred):
(function() {
var iframe= document.createElement('iframe');
iframe.src= 'http://www.example.com/myframe';
iframe.width=iframe.height= 100;
document.getElementById('examplecomframe').appendChild(iframe);
})();
Or to insert just before the current script:
var scripts= document.getElementsByTagName('script');
var script= scripts[scripts.length-1];
script.parentNode.insertBefore(iframe, script);
I wouldn't use jQuery for third-party script inclusion. You'd have to load the whole heavy framework into the enclosing page, just for the sake of a few lines of JS. This can cause clashes with other frameworks (or different versions of jQuery) being used by the host page, something very rude for a third-party script to do.
I think you may have how this is working a bit mixed up. The way it's working is this:
1. User requests page from your domain/server, page is served.
2. Client web browser on users machine interprets said page, if a script block includes a reference to a js file at some other location then said js file is fetched.
3. Javascript is processed by the clients browser.
So really all you need is a JS file (plain old ASCII) on the server and have it do some document.write() calls to add the code you want it to add, for example:
go to http://www.shaunhusain.com/TestIFrameViaJS
three files there involved
index.html
anotherpage.html
testIFrame.js
let me know if it doesn't work out or I took a wrong direction for what you're looking for?
Shaun
To generate a Tag with jQuery you can use $('<tagname />') and pass an object with parameters (for example src).
Afterwards you append this iframe to the Dom. Using html() you can set the html-content of a selected element (in this case a tag with id example) to your iframe.
$(function() {
var iframe = $('<iframe />', {
src: 'http://example.com',
width: 100,
height: 100
});
$('#example').html(iframe);
});
http://api.fatherstorm.com/test/4159620.php
using jQuery for this...
$(document).ready(function() {
$('#fb-root').append('<iframe/>');
$('#fb-root iframe')
.attr('id','my_iframe')
.attr('src','http://www.cnn.com')
.css('width','100%')
.css('height','100%')
.attr('frameborder','no');
});

Categories

Resources