Detecting if YouTube is blocked by company / ISP - apache-flex

We have YouTube videos on a site and want to detect if it is likely that they will not be able to view them due to (mostly likely) company policy or otherwise.
We have two sites:
1) Flex / Flash
2) HTML
I think with Flex I can attempt to download http://youtube.com/crossdomain.xml and if it is valid XML assume the site is available
But with HTML I don't know how to do it. I can't even think of a 'nice hack'.

I like lacker's solution, but yes, it creates a race condition.
This will work and won't create a race contition:
var image = new Image();
image.onload = function(){
// The user can access youtube
};
image.onerror = function(){
// The user can't access youtube
};
image.src = "http://youtube.com/favicon.ico";

You can load an image from youtube using javascript and check its properties. The favicon is tiny and has a consistent url -
var image = new Image();
image.src = "http://youtube.com/favicon.ico";
if (image.height > 0) {
// The user can access youtube
} else {
// The user can't access youtube
}
I think this is slightly better than loading javascript because this won't try to run any code, and while youtube might rename their javascript files, or functions from those files, they are unlikely to ever rename their favicon.

This should work. Basically, it loads a youtube.com javascript file, then checks if a function in that file exists.
<html>
<head>
<script src="http://www.youtube.com/js/account.js"></script>
<script>
function has_you_tube()
{
if(typeof addVideosToQuicklist == 'function')
{
return true;
}
else
{
return false;
}
}
</script>
</head>
<body>
<script>alert( "has_youtube: " + has_you_tube() ); </script>
</body>
</html>

I got stuck on this today and tried the favicon test but it wasnt working in IE. I was using the YouTube Player API Reference for iframe Embeds to embed youtube videos into my site so what I did is perform a check on the player var defined just before the onYouTubeIFrameReady with a delay on the javascript call.
<script> function YouTubeTester() {
if (player == undefined) {
alert("youtube blocked");
}
}
</script>
<script>window.setTimeout("YouTubeTester()", 500);</script>
Seems to work for me. I needed the delay to get it to work in IE.

This worked for me... Its also my first post, hope it helps some one too.
<?php
$v = file_get_contents("https://www.youtube.com/iframe_api");
//Tie counts to a variable
$test = substr_count($v, 'loading');
if ($test > 0)
{ ?>
<iframe>YOUTUBE VIDEO GOES HERE</iframe>
<?php
}
else
{
echo "<br/> no connection";
}
?>

Related

Excluding bootstrap from specific routes in Meteor

I was hoping anyone could give some input on this,
I'm creating a meteor app in which I would like to use bootstrap to creating the admin environment, but have the visitor facing side using custom css. When I add the bootstrap package to my app using meteor it's available on every page, is there a way to restrict the loading of bootstrap to routes that are in '/admin' ?
When you add bootstrap package it's not possible. You can, however, add bootstrap csses to public directory and then load them in a header subtemplate that will only be rendered when you're in the dashboard.
EDIT
But then how would you go about creating seperate head templates?
Easy:
<head>
...
{{> adminHeader}}
...
</head>
<template name="adminHeader">
{{#if adminPage}}
... // Put links to bootstrap here
{{/if}}
</template>
Template.adminHeader.adminPage = function() {
return Session.get('adminPage');
}
Meteor.router.add({
'/admin': function() {
Session.set('adminPage', true);
...
}
});
DISCLAIMER: I am unsure of a 'meteor way' to do this, so here is how I would do it with plain JS.
jQuery
$("link[href='bootstrap.css']").remove();
JS - Credit to javascriptkit
function removejscssfile(filename, filetype){
var targetelement=(filetype=="js")? "script" : (filetype=="css")? "link" : "none" //determine element type to create nodelist from
var targetattr=(filetype=="js")? "src" : (filetype=="css")? "href" : "none" //determine corresponding attribute to test for
var allsuspects=document.getElementsByTagName(targetelement)
for (var i=allsuspects.length; i>=0; i--){ //search backwards within nodelist for matching elements to remove
if (allsuspects[i] && allsuspects[i].getAttribute(targetattr)!=null && allsuspects[i].getAttribute(targetattr).indexOf(filename)!=-1)
allsuspects[i].parentNode.removeChild(allsuspects[i]) //remove element by calling parentNode.removeChild()
}
}
removejscssfile("bootstrap.css", "css")
However, doing that would complete remove it from the page. I am not sure whether meteor would then try to readd it when a user goes to another page. If that does not automatically get readded, then you have an issue of bootstrap not being included when someone goes from the admin section to the main site, which would break the look of the site.
The way I would get around that would be to disable and enable the stylesheets:
Meteor.autorun(function(){
if(Session.get('nobootstrap')){
$("link[href='bootstrap.css']").disabled = true;
}else{
$("link[href='bootstrap.css']").disabled = false;
}
});
There my be other bootstrap resources which may need to be removed, take a look at what your page is loading.
To use jQuery in the same way but for the javascript files, remember to change link to script and href to src
From my tests, Meteor does not automatically re-add the files once they have been removed so you would need to find some way of re-adding them dynamically if you want the same user to be able to go back and forth between the main site and the admin site. Or simply if the http referrer to the main site is from the admin, force reload the page and then the bootstrap resources will load and everything will look pretty.
P.s. make sure you get the href correct for the jQuery version
If somebody is interested in including any js/css files, I've written a helper for it:
if (Meteor.isClient) {
// dynamic js / css include helper from public folder
Handlebars.registerHelper("INCLUDE_FILES", function(files) {
if (files != undefined) {
var array = files.split(',');
array.forEach(function(entity){
var regex = /(?:\.([^.]+))?$/;
var extension = regex.exec(entity)[1];
if(extension == "js"){
$('head').append('<script src="' + entity + '" data-dynamicJsCss type="text/javascript" ></script>');
} else if (extension == "css"){
$('head').append('<link href="' + entity + '" data-dynamicJsCss type="text/css" rel="stylesheet" />');
};
});
}
});
Router.onStop(function(){
$("[data-dynamicJsCss]").remove();
});
}
Then simply use:
{{INCLUDE_FILES '/css/html5reset.css, /js/test.js'}}
in any of your loaded templates :)

hide iframe url in HTML source code

How to hide iframe url From HTML source code?
<iframe src="http://mysite.com" frameborder="0" scrolling="no" width="728" height="90"></iframe>
You can use javascript to load the source, and it will not be visible in iframe url in page source code.
For example with jQuery:
<script type="text/javascript">
$(document).ready(function(e) {
$('iframe').attr('src','http://www.flickr.com/');
});
</script>
<body>
<iframe src="" />
</body>
Example here.
You can combine it with $.post to get the value serverside:
$.post('get-iframe-src.php', function(data) {
$('iframe').attr('src',data);
});
You can even load iframe itself to some element like:
$.post('get-iframe.php', function(data) {
$('#element_id').html(data);
});
etc. solutions are many, this is just one of.
You can't. If the URL isn't in the HTML, how would the browser know where to get it?
One thing you could try is to obscure it to make it slightly harder for someone to find it. You could have the src attribute be blank and then when the document is ready fetch the URL value from the server in a separate AJAX request and update the iframe tag to include that value in the src.
This would be a fair amount of work, however, and wouldn't really accomplish anything. The only thing it would prevent is somebody finding it by viewing the page source. They can still look at the "current version" of the HTML in any web browser's debugging tools. (Right click on an element and inspect it, which is nearly ubiquitous at this point.) Or any other normal traffic-sniffing tools will see it plain as day.
Ultimately, if the web browser needs to know a piece of information, then that information needs to be visible on the client-side.
There's no way to fully block source viewing. But there are a couple ways to disable right-clicking:
1) Javascript:
<script language="JavaScript">
<!--
var message="Your message goes here.";
function click(e) {
if (document.all) {
if (event.button == 2) {
alert(message);
return false;
}
}
if (document.layers) {
if (e.which == 3) {
alert(message);
return false;
}
}
}
if (document.layers) {
document.captureEvents(Event.MOUSEDOWN);
}
document.onmousedown=click;
// -->
2) Add the following into your tag: oncontextmenu="return false"
reference https://forum.powweb.com/archive/index.php/t-36161.html
I decided for solution that does not use javascript, because most of the time it will be possible to read the "hidden" content.
Moreover, changing iframe SRC with javascript, will keep URL hidden when checking the source. However, inspecting the code will show the real URL.
My code is in PHP; however, I believe that the logic can be translated to other programming languages. This is how it works:
I kept the iframe tag as usual:
<iframe src="dash_url.php"></iframe>
The trick is inside the iframe_url.php, where I validate the referer. If it is valid, page is redirected to iframe URL. If it is not, than URL will be a message.
<?
$iframe_url = "https://example.com";
$Referer = #$_SERVER["HTTP_REFERER"];
$RefererHost = #explode(":", explode("/", explode("//", $Referer)[1])[0])[0];
if ($RefererHost == $_SERVER["SERVER_NAME"]) {
header("Location: " . $iframe_url);
} else {
echo "Invalid URL";
}
?>
If visitor inspects the page or checks the source, iframe tag will show SRC as dash_url.php.

Image load timeout in Internet Explorer

I have a page for an internal app that displays document images streamed from a document storage system using a web service. The problem I am having is that when a user does their search they may get hundreds of hits, which I have to display on one large page so they can print them all. This works fine in Firefox, but in IE it stops loading the images after a while so I get a hundred or so displayed and the rest just have the broken image symbol. Is there a setting somewhere that I can change this timeout?
If the issue is indeed a timeout, you might be able to work around it by using a "lazy load" script and adding new images to the document only after existing images have loaded.
There are a lot of ways to do this, but here's a simple example I threw together and tested. Instead of this:
<img src="image001.jpg" />
<img src="image002.jpg" />
<img src="image003.jpg" />
<img src="image004.jpg" />
<!-- Etc etc etc -->
You could do this:
<div id="imgsGoHere">
</div>
<script type="text/javascript">
function crossBrowserEventAttach(objectRef, eventName, functionRef)
{
try {
objectRef.addEventListener(eventName, functionRef, false);
}
catch(err) {
try {
objectRef.attachEvent("on" + eventName, functionRef);
}
catch(err2) {
// event attachment failed
}
}
}
function addImageToPage()
{
var newImageElement = document.createElement("img");
newImageElement.src = imageArray[nextImageNumber];
var targetElement = document.getElementById("imgsGoHere");
targetElement.appendChild(newImageElement);
nextImageNumber++;
if (nextImageNumber < imageArray.length) {
crossBrowserEventAttach(newImageElement, "load", addImageToPage);
crossBrowserEventAttach(newImageElement, "error", addImageToPage);
}
}
var nextImageNumber = 0;
var imageArray = new Array();
imageArray[imageArray.length] = "image001.jpg";
imageArray[imageArray.length] = "image002.jpg";
imageArray[imageArray.length] = "image003.jpg";
// .
// .
// .
// Snip hundreds of rows
// .
// .
// .
imageArray[imageArray.length] = "image999.jpg";
addImageToPage();
</script>
Each image is added to the page only after the previous image loads (or fails to load). If your browser is timing out, I think that will fix it.
Of course, the problem might actually not be a timeout, but rather that you're running out of memory/system resources and IE is giving up. Or there might be an IE DOM limitation like Sra said.
No final solution, but some hints...
I think the ie Dom hangs up. I,ve seen this in other cases. I needed simply to show the images and used a js which loads the image the time they came into focus, but that want work if you directly hit print I think. Can you use the new css ability to store imagedata directly instead of links. That should solve your problem. I am not quite sure but I think it is supported since ie 7
My guess is that you have to work around the IE setting, the easiest way to do it is simply not showing images that are not loaded or replacing them with a default image:
your html:
<img src="http://domain.com/image.jpg" />
your js:
$('img').load(function(){
// ... loaded
}).error(function(){
// ... not loaded, replace
$(this).attr('src','/whatever/default.jpg');
// ... not loaded, hide
$(this).hide();
});
That is a problem with microsoft. Unfortunately, this is a setting that would have to be changed on every single computer, as there is no remote way to alter it. To change it on your computer, try opening regedit and adding the RecieveTimeout DWORD with a Value of (#of minutes)*6000. Hope this helps-CodeKid1001
Edit: Sorry about that, I forgot to put in the file path:
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\InternetSettings
I used something similar to laod HD pictures as a background using ASP Pages
But i used jQuery to handle the images and its loading. This is a sample for 1 image but with a bit of tweaking you can load dynamically
myImage = new Image();
$(myImage).load(function ()
{
$(this).hide(); //Stops the loading effect of large images. can be removed
$('.csBackground li').append(this); //Append image to where you need it
$(myImage).show();
}).attr('src', settings.images[0]) //I pass an array from ASP code behind so 0 can be 'i'
.error( function { checkImages(); } ) //try and relaod the image or something?
So instead of changing the timeout- just try and reload the images on error.
Otherwise i only found a solution that is client specific (HTTP Timeout)
http://support.microsoft.com/kb/813827

Is there a cross-domain iframe height auto-resizer that works?

I tried a few solutions but wasn't successful. I'm wondering if there is a solution out there preferably with an easy-to-follow tutorial.
You have three alternatives:
1. Use iFrame-resizer
This is a simple library for keeping iFrames sized to their content. It uses the PostMessage and MutationObserver APIs, with fall backs for IE8-10. It also has options for the content page to request the containing iFrame is a certain size and can also close the iFrame when your done with it.
https://github.com/davidjbradshaw/iframe-resizer
2. Use Easy XDM (PostMessage + Flash combo)
Easy XDM uses a collection of tricks for enabling cross-domain communication between different windows in a number of browsers, and there are examples for using it for iframe resizing:
http://easyxdm.net/wp/2010/03/17/resize-iframe-based-on-content/
http://kinsey.no/blog/index.php/2010/02/19/resizing-iframes-using-easyxdm/
Easy XDM works by using PostMessage on modern browsers and a Flash based solution as fallback for older browsers.
See also this thread on Stackoverflow (there are also others, this is a commonly asked question). Also, Facebook would seem to use a similar approach.
3. Communicate via a server
Another option would be to send the iframe height to your server and then poll from that server from the parent web page with JSONP (or use a long poll if possible).
I got the solution for setting the height of the iframe dynamically based on it's content. This works for the cross domain content.
There are some steps to follow to achieve this.
Suppose you have added iframe in "abc.com/page" web page
<div>
<iframe id="IframeId" src="http://xyz.pqr/contactpage" style="width:100%;" onload="setIframeHeight(this)"></iframe>
</div>
Next you have to bind windows "message" event under web page "abc.com/page"
window.addEventListener('message', function (event) {
//Here We have to check content of the message event for safety purpose
//event data contains message sent from page added in iframe as shown in step 3
if (event.data.hasOwnProperty("FrameHeight")) {
//Set height of the Iframe
$("#IframeId").css("height", event.data.FrameHeight);
}
});
On iframe load you have to send message to iframe window content with "FrameHeight" message:
function setIframeHeight(ifrm) {
var height = ifrm.contentWindow.postMessage("FrameHeight", "*");
}
On main page that added under iframe here "xyz.pqr/contactpage" you have to bind windows "message" event where all messages are going to receive from parent window of "abc.com/page"
window.addEventListener('message', function (event) {
// Need to check for safety as we are going to process only our messages
// So Check whether event with data(which contains any object) contains our message here its "FrameHeight"
if (event.data == "FrameHeight") {
//event.source contains parent page window object
//which we are going to use to send message back to main page here "abc.com/page"
//parentSourceWindow = event.source;
//Calculate the maximum height of the page
var body = document.body, html = document.documentElement;
var height = Math.max(body.scrollHeight, body.offsetHeight,
html.clientHeight, html.scrollHeight, html.offsetHeight);
// Send height back to parent page "abc.com/page"
event.source.postMessage({ "FrameHeight": height }, "*");
}
});
What I did was compare the iframe scrollWidth until it changed size while i incrementally set the IFrame Height. And it worked fine for me. You can adjust the increment to whatever is desired.
<script type="text/javascript">
function AdjustIFrame(id) {
var frame = document.getElementById(id);
var maxW = frame.scrollWidth;
var minW = maxW;
var FrameH = 100; //IFrame starting height
frame.style.height = FrameH + "px"
while (minW == maxW) {
FrameH = FrameH + 100; //Increment
frame.style.height = FrameH + "px";
minW = frame.scrollWidth;
}
}
</script>
<iframe id="RefFrame" onload="AdjustIFrame('RefFrame');" class="RefFrame"
src="http://www.YourUrl.com"></iframe>
I have a script that drops in the iframe with it's content. It also makes sure that iFrameResizer exists (it injects it as a script) and then does the resizing.
I'll drop in a simplified example below.
// /js/embed-iframe-content.js
(function(){
// Note the id, we need to set this correctly on the script tag responsible for
// requesting this file.
var me = document.getElementById('my-iframe-content-loader-script-tag');
function loadIFrame() {
var ifrm = document.createElement('iframe');
ifrm.id = 'my-iframe-identifier';
ifrm.setAttribute('src', 'http://www.google.com');
ifrm.style.width = '100%';
ifrm.style.border = 0;
// we initially hide the iframe to avoid seeing the iframe resizing
ifrm.style.opacity = 0;
ifrm.onload = function () {
// this will resize our iframe
iFrameResize({ log: true }, '#my-iframe-identifier');
// make our iframe visible
ifrm.style.opacity = 1;
};
me.insertAdjacentElement('afterend', ifrm);
}
if (!window.iFrameResize) {
// We first need to ensure we inject the js required to resize our iframe.
var resizerScriptTag = document.createElement('script');
resizerScriptTag.type = 'text/javascript';
// IMPORTANT: insert the script tag before attaching the onload and setting the src.
me.insertAdjacentElement('afterend', ifrm);
// IMPORTANT: attach the onload before setting the src.
resizerScriptTag.onload = loadIFrame;
// This a CDN resource to get the iFrameResizer code.
// NOTE: You must have the below "coupled" script hosted by the content that
// is loaded within the iframe:
// https://unpkg.com/iframe-resizer#3.5.14/js/iframeResizer.contentWindow.min.js
resizerScriptTag.src = 'https://unpkg.com/iframe-resizer#3.5.14/js/iframeResizer.min.js';
} else {
// Cool, the iFrameResizer exists so we can just load our iframe.
loadIFrame();
}
}())
Then the iframe content can be injected anywhere within another page/site by using the script like so:
<script
id="my-iframe-content-loader-script-tag"
type="text/javascript"
src="/js/embed-iframe-content.js"
></script>
The iframe content will be injected below wherever you place the script tag.
Hope this is helpful to someone. 👍
I ran into this issue while working on something at work (using React). Basically, we have some external html content that we save into our document table in the database and then insert onto the page under certain circumstances when you're in the Documents dataset.
So, given n inlines, of which up to n could contain external html, we needed to devise a system to automatically resize the iframe of each inline once the content fully loaded in each. After spinning my wheels for a bit, this is how I ended up doing it:
Set a message event listener in the index of our React app which checks for a a specific key that we will set from the sender iframe.
In the component that actually renders the iframes, after inserting the external html into it, I append a <script> tag that will wait for the iframe's window.onload to fire. Once that fires, we use postMessage to send a message to the parent window with information about the iframe id, computed height, etc.
If the origin matches and the key is satisfied in the index listener, grab the DOM id of the iframe that we pass in the MessageEvent object
Once we have the iframe, just set the height from the value that is passed from the iframe postMessage.
// index
if (window.postMessage) {
window.addEventListener("message", (messageEvent) => {
if (
messageEvent.data.origin &&
messageEvent.data.origin === "company-name-iframe"
) {
const iframe = document.getElementById(messageEvent.data.id)
// this is the only way to ensure that the height of the iframe container matches its body height
iframe.style.height = `${messageEvent.data.height}px`
// by default, the iframe will not expand to fill the width of its parent
iframe.style.width = "100%"
// the iframe should take precedence over all pointer events of its immediate parent
// (you can still click around the iframe to segue, for example, but all content of the iframe
// will act like it has been directly inserted into the DOM)
iframe.style.pointerEvents = "all"
// by default, iframes have an ugly web-1.0 border
iframe.style.border = "none"
}
})
}
// in component that renders n iframes
<iframe
id={`${props.id}-iframe`}
src={(() => {
const html = [`data:text/html,${encodeURIComponent(props.thirdLineData)}`]
if (window.parent.postMessage) {
html.push(
`
<script>
window.onload = function(event) {
window.parent.postMessage(
{
height: document.body.scrollHeight,
id: "${props.id}-iframe",
origin: "company-name-iframe",
},
"${window.location.origin}"
);
};
</script>
`
)
}
return html.join("\n")
})()}
onLoad={(event) => {
// if the browser does not enforce a cross-origin policy,
// then just access the height directly instead
try {
const { target } = event
const contentDocument = (
target.contentDocument ||
// Earlier versions of IE or IE8+ where !DOCTYPE is not specified
target.contentWindow.document
)
if (contentDocument) {
target.style.height = `${contentDocument.body.scrollHeight}px`
}
} catch (error) {
const expectedError = (
`Blocked a frame with origin "${window.location.origin}" ` +
`from accessing a cross-origin frame.`
)
if (error.message !== expectedError) {
/* eslint-disable no-console */
console.err(
`An error (${error.message}) ocurred while trying to check to see ` +
"if the inner iframe is accessible or not depending " +
"on the browser cross-origin policy"
)
}
}
}}
/>
Here is an alternative implementation.
Basically if you able to edit page at other domain you can place another iframe page that belongs to your server which saving height to cookies.
With an interval read cookies when it is updated, update the height of the iframe. That is all.
Edit: 2019 December
The solution above basically uses another iframe inside of an iframe 3rd iframe is belongs to the top page domain, which you call this page with a query string that saves size value to a cookie, outer page checks this query with some interval. But it is not a good solution so you should follow this one:
In Top page :
window.addEventListener("message", (m)=>{iframeResizingFunction(m)});
Here you can check m.origin to see where is it comes from.
In frame page:
window.parent.postMessage({ width: 640, height:480 }, "*")
Although, please don't forget this is not so secure way. To make it secure update * value (targetOrigin) with your desired value.
Please follow documentation: https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage
I found another server side solution for web dev using PHP to get the size of an iframe.
First is using server script PHP to an external call via internal function: (like a file_get_contents with but curl and dom).
function curl_get_file_contents($url,$proxyActivation=false) {
global $proxy;
$c = curl_init();
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($c, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US; rv:1.8.1.7) Gecko/20070914 Firefox/2.0.0.7");
curl_setopt($c, CURLOPT_REFERER, $url);
curl_setopt($c, CURLOPT_URL, $url);
curl_setopt($c, CURLOPT_FOLLOWLOCATION, 1);
if($proxyActivation) {
curl_setopt($c, CURLOPT_PROXY, $proxy);
}
$contents = curl_exec($c);
curl_close($c);
$dom = new DOMDocument();
$dom->preserveWhiteSpace = false;
#$dom->loadHTML($contents);
$form = $dom->getElementsByTagName("body")->item(0);
if ($contents) //si on a du contenu
return $dom->saveHTML();
else
return FALSE;
}
$url = "http://www.google.com"; //Exernal url test to iframe
<html>
<head>
<script type="text/javascript">
</script>
<style type="text/css">
#iframe_reserve {
width: 560px;
height: 228px
}
</style>
</head>
<body>
<div id="iframe_reserve"><?php echo curl_get_file_contents($url); ?></div>
<iframe id="myiframe" src="http://www.google.com" scrolling="no" marginwidth="0" marginheight="0" frameborder="0" style="overflow:none; width:100%; display:none"></iframe>
<script type="text/javascript">
window.onload = function(){
document.getElementById("iframe_reserve").style.display = "block";
var divHeight = document.getElementById("iframe_reserve").clientHeight;
document.getElementById("iframe_reserve").style.display = "none";
document.getElementById("myiframe").style.display = "block";
document.getElementById("myiframe").style.height = divHeight;
alert(divHeight);
};
</script>
</body>
</html>
You need to display under the div (iframe_reserve) the html generated by the function call by using a simple echo curl_get_file_contents("location url iframe","activation proxy")
After doing this a body event function onload with javascript take height of the page iframe just with a simple control of the content div (iframe_reserve)
So I used divHeight = document.getElementById("iframe_reserve").clientHeight; to get height of the page external we are going to call after masked the div container (iframe_reserve). After this we load the iframe with its good height that's all.

Get Image dimensions using Javascript during file upload

I have file upload UI element in which the user will upload images. Here I have to validate the height and width of the image in client side. Is it possible to find the size of the image having only the file path in JS?
Note: If No, is there any other way to find the dimensions in Client side?
You can do this on browsers that support the new File API from the W3C, using the readAsDataURL function on the FileReader interface and assigning the data URL to the src of an img (after which you can read the height and width of the image). Currently Firefox 3.6 supports the File API, and I think Chrome and Safari either already do or are about to.
So your logic during the transitional phase would be something like this:
Detect whether the browser supports the File API (which is easy: if (typeof window.FileReader === 'function')).
If it does, great, read the data locally and insert it in an image to find the dimensions.
If not, upload the file to the server (probably submitting the form from an iframe to avoid leaving the page), and then poll the server asking how big the image is (or just asking for the uploaded image, if you prefer).
Edit I've been meaning to work up an example of the File API for some time; here's one:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title>Show Image Dimensions Locally</title>
<style type='text/css'>
body {
font-family: sans-serif;
}
</style>
<script type='text/javascript'>
function loadImage() {
var input, file, fr, img;
if (typeof window.FileReader !== 'function') {
write("The file API isn't supported on this browser yet.");
return;
}
input = document.getElementById('imgfile');
if (!input) {
write("Um, couldn't find the imgfile element.");
}
else if (!input.files) {
write("This browser doesn't seem to support the `files` property of file inputs.");
}
else if (!input.files[0]) {
write("Please select a file before clicking 'Load'");
}
else {
file = input.files[0];
fr = new FileReader();
fr.onload = createImage;
fr.readAsDataURL(file);
}
function createImage() {
img = document.createElement('img');
img.onload = imageLoaded;
img.style.display = 'none'; // If you don't want it showing
img.src = fr.result;
document.body.appendChild(img);
}
function imageLoaded() {
write(img.width + "x" + img.height);
// This next bit removes the image, which is obviously optional -- perhaps you want
// to do something with it!
img.parentNode.removeChild(img);
img = undefined;
}
function write(msg) {
var p = document.createElement('p');
p.innerHTML = msg;
document.body.appendChild(p);
}
}
</script>
</head>
<body>
<form action='#' onsubmit="return false;">
<input type='file' id='imgfile'>
<input type='button' id='btnLoad' value='Load' onclick='loadImage();'>
</form>
</body>
</html>
Works great on Firefox 3.6. I avoided using any library there, so apologies for the attribute (DOM0) style event handlers and such.
The previous example is Okay, but it is far from perfect.
var reader = new FileReader();
reader.onload = function(e)
{
var image = new Image();
image.onload = function()
{
console.log(this.width, this.height);
};
image.src = e.target.result;
};
reader.readAsDataURL(this.files[0]);
If you use a flash based uploaded such as SWFUpload you can have all the info you want as well as multiple queued uploads.
I recommend SWFUpload and am in no way associated with them other than as a user.
You could also write a silverlight control to pick your file and upload it.
No, You can't, filename and file content are send to the server in http headerbody, javascript cannot manipulate those fields.
HTML5 is definitely the correct solution here.
You should always code for the future, not the past.
The best way to deal with HTML4 browsers is to either fall back on degraded functionality or use Flash (but only if the browser does not support the HTML5 file API)
Using the img.onload event will enable you to recover the dimensions of the file.
Its working for an app I'm working on.

Resources