how to detect if a URL points to a SWF - javascript

Is there a way (preferrably using JavaScript) to determine whether a URL is to a SWF or a JPG?
The obvious answer is to sniff the filename for ".jpg" or ".swf" but I'm dealing with banners that are dynamically decided by the server and usually have a lot of parameters and generally don't include an extension.
so i'm wondering if I could load the file first and then read it somehow to determine whether it's SWF or JPG, and then place it, because the JavaScript code I'd need to display a JPG vs a SWF is very different.
Thanks!

You could use javascript to detect if it is a image by creating a dynamic img-tag.
function isImage(url, callback) {
var img = document.createElement('img');
img.onload = function() {
callback(url);
}
img.src = url;
}
And then calling it with:
isImage('http://animals.nationalgeographic.com/staticfiles/NGS/Shared/StaticFiles/animals/images/primary/bald-eagle-head.jpg', function(url) { alert(url + ' is a image'); });
Update
This version will always execute the callback with a boolean value.
function isImage(url) {
var img = document.createElement('img');
img.onload = function() {
isImageCallback(url, true);
}
img.onerror = function() {
isImageCallback(url, false);
}
img.src = url;
}
function isImageCallback(url, result) {
if (result)
alert(url + ' is an image');
else
alert(url + ' is not an image');
}
Put your logic in the isImageCallback function.

I would extend Sijin's answer by saying:
An HTTP HEAD request to the url can be used to examine the resource's mime-type. You
won't need to download the rest of the file that way.

Completely untested, basicly just an idea:
function isImage(url)
{
var http = getHTTPObject();
http.onreadystatechange = function ()
{
if (http.readyState == 4)
{
var contentType = http.getResponseHeader("Content Type");
if (contentType == "image/gif" || contentType == "image/jpeg")
return true;
else
return false;
}
}
http.open("HEAD",url,true);
http.send(null);
}
function getHTTPObject()
{
if (window.XMLHttpRequest)
{
return new XMLHttpRequest();
}
else
{
if (window.ActiveXObject)
{
return new ActiveXObject("Microsoft.XMLHTTP");
}
}
return false;
}

I am not sure the of the exact setup you have, but can you use the HTTP response and check the mime-type to determine image vs flash?

If the URL doesn't have an extension then there is no way to tell without requesting the file from the server.

Related

How do I fetch all images in a folder with AJAX using pure JS?

I'm trying to get all the images in a folder with an AJAX request (for use in an image slider). I've found this jQuery solution which works perfectly fine, except that it uses jQuery. What would a pure JS equivalent look like? (i.e. XMLHttpRequest)
Thanks to #FZs help this is what I ended up with. Thank you!
var xhr = new XMLHttpRequest();
xhr.open("GET", "/img", true);
xhr.responseType = 'document';
xhr.onload = () => {
if (xhr.status === 200) {
var elements = xhr.response.getElementsByTagName("a");
for (x of elements) {
if ( x.href.match(/\.(jpe?g|png|gif)$/) ) {
let img = document.createElement("img");
img.src = x.href;
document.body.appendChild(img);
}
};
}
else {
alert('Request failed. Returned status of ' + xhr.status);
}
}
xhr.send()
You can do it without jQuery! Maybe with more code, but this should work (adapted from this post)):
var folder = "images/";
var ajax=new XMLHttpRequest()
ajax.open("GET",folder,true)
ajax.onload=function () {
var elements=(new DOMParser()).parseFromString(ajax.responseText,"text/html").getElementsByTagname("A")
for(x of elements){
if(request.status[0]==2 && x.href.match(/\.(jpe?g|png|gif)$/)) {
let img=document.createElement("IMG")
img.src=folder+x.href
document.body.appendChild(img);
}
};
}
ajax.send()
Or, you can force XMLHttpRequest to parse document (idea from #Rainman's comment):
ajax.responseType = "document"
So the code becomes to the following:
var folder = "images/";
var ajax=new XMLHttpRequest()
ajax.open("GET",folder,true)
ajax.onload=function () {
ajax.responseType="document"
var elements=ajax.responseText.getElementsByTagname("A")
for(x of elements){
if(request.status[0]==2 && x.href.match(/\.(jpe?g|png|gif)$/)) {
let img=document.createElement("IMG")
img.src=folder+x.href
document.body.appendChild(img);
}
};
}
ajax.send()

XMLHttpRequest not working with FileReader

I have a form in which the user can upload images and pdf-files. Right now I'm trying to convert the pdf-files into jpg-files, in order to be able to preview them BEFORE the form gets submitted.
Here is the form:
<form>
<div class="fileUpload">
<p class="fileformats">Valid formats: jpg/png/gif/jpeg/pdf</p><br>
<input type="file" name="overlayfile[]" class="src" onchange="preview(this)">
<img src="img/someimage.jpg" class="target"/>
</div>
</form>
<p id="item"></p>
The JavaScript Code which I use to preview the files and to send the XMLHttpRequest:
function preview(input) {
if(input.files && input.files[0]) {
var reader = new FileReader();
if(input.files[0].type == "image/jpeg" || input.files[0].type == "image/gif") {
reader.onload = function(e) {
input.nextElementSibling.src = e.target.result;
}
reader.readAsDataURL(input.files[0]);
} else if (input.files[0].type == "application/pdf") {
reader.onload = function(e) {
var targeturl = e.target.result;
getURL(targeturl);
}
}
}
}
function getURL (item) {
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
if(request.readyState == 4 && request.status == 200) {
document.getElementById("item").innerHTML = request.responseText;
}
}
request.open("GET", "preview.php?url="+item, true);
request.send();
}
(I did not write the function to convert the pdf-file into an image yet, currently I'm simply trying to pass the value of target as the content of my paragraph. I'm doing this because I would like to do it step by step so I do not miss any mistakes that would be very annoying later).
When I declare a variable in my getURL() function, it works just fine and the paragraph displays the value of the variable, however, when I call the function from within reader.onload nothing happens.
Does anyone know why that is and how I can fix that?
If you need anymore code/ further explanations please let me know and thank you very much in advance for your help.
Perhaps you don't need to upload them to the server. You could just create a iframe and show it.
Also, you don't need the filereader, creating a objectURL instead. It is faster and better. base64 is ~3 times larger and takes time to (de)compile.
function preview(input) {
const URL = window.URL || window.webkitURL
Array.from(input.files).forEach(file => {
if (file.type.startsWith('image')) {
input.nextElementSibling.src = URL.createObjectURL(file)
} else if (file.type == 'application/pdf') {
let iframe = document.createElement('iframe')
iframe.src = URL.createObjectURL(file)
iframe.onload = function() {
document.getElementById("item").appendChild(iframe)
}
iframe.onerror = function(){
// failed to load pdf
}
}
})
}
if the iframe don't work for you due to something... POST the file to preview.php instead of sending it as base64 using xhr.send(file)

Pass image src to function instead of files

So I have a webpage with two image elements. It is basically a website where you upload an image and it encrypts a secret massage with steganography. I want to show the difference that is not otherwise visible and I found Resemble.js which is a library to compare images. It gets two files as arguments and I would like to use my image sources instead of files since I don't want to save the images generated.
To sum up, I want to get rid of the requests and get my images via sources in the HTML but I don't know how to get it to work with Resemble.js since it accepts only files.
How the second image is generated:
cover.src = steg.encode(textarea.value, img, {
"width": img.width,
"height": img.height
});
The JavaScript working with files:
(function () {
var xhr = new XMLHttpRequest();
var xhr2 = new XMLHttpRequest();
var done = $.Deferred();
var dtwo = $.Deferred();
try {
xhr.open('GET', 'static/original.png', true);
xhr.responseType = 'blob';
xhr.onload = function (e) { done.resolve(this.response); };
xhr.send();
xhr2.open('GET', 'static/encoded.png', true);
xhr2.responseType = 'blob';
xhr2.onload = function (e) { dtwo.resolve(this.response); };
xhr2.send();
} catch (err) {
alert(err);
}
$('#example-images').click(function () {
$.when(done, dtwo).done(function (file, file1) {
if (typeof FileReader === 'undefined') {
resembleControl = resemble('./static/original.png')
.compareTo('./static/encoded.png')
.onComplete(onComplete);
} else {
resembleControl = resemble(file)
.compareTo(file1)
.onComplete(onComplete);
}
});
return false;
});
}());

ajax - javascript function to refresh a div

I'm trying to have a div refresh after a callback using ajax functions. Basically, I want /includes/view_game/achievements.inc.php to be reloaded in the div #achievements_tab. The callback (I didn't include it in codes below) works well and triggers the AchievementRefresh function found below (the opacity of the div changes to 0.5, but it remains like this and the refresh is not made).
Those two functions are used for another similar ajax refresh on my site that works well. So I tried to modify the code, but since it's for a slightly different purpose, maybe I have the wrong approach.
function AjaxPost(url, success_function) {
xmlHttp = GetXmlHttpObject();
if (xmlHttp == null) {
alert("Your browser doesn't support AJAX. You should upgrade it!")
return
}
xmlHttp.onreadystatechange = success_function;
xmlHttp.open("POST", url, true);
xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
}
This AjaxPost function is used in the other function below:
function AchievementRefresh() {
div('achievements_tab').style.opacity = 0.5;
div('highscore_pages').innerHTML = '<img src="'+site_url+'/images/loader.gif" />';
AjaxPost(site_url+"/includes/view_game/achievements.inc.php?", '',
function () {
div('achievements_tab').innerHTML = xmlHttp.responseText;
div('achievements_tab').style.opacity = 1;
}
)
}
Use load
$('#achievements_tab').load('/includes/view_game/achievements.inc.php');
See: http://api.jquery.com/load/
Edit
E.g.
function AchievementRefresh() {
$('#achievements_tab').css('opacity', 0.5);
$('#highscore_pages').html('<img src="'+site_url+'/images/loader.gif" />');
$('#achievements_tab').load('/includes/view_game/achievements.inc.php')
.success(function() {
$('#achievements_tab').css('opacity', 1);
});
}
Try this.
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
div('achievements_tab').innerHTML = xmlHttp.responseText;
div('achievements_tab').style.opacity = 1;
}
}
};`
Name and id is example.
Also, some changes:
AjaxPost(site_url+"/includes/view_game/achievements.inc.php");
var params= 'name'+encodeURIComponent(name)+'&id='+encodeURIComponent(id)
Parameters shouldn't be in URL.
xmlhttp.send(params);

With javascript, how do you get final result URL after 302 redirect on img src?

If there is an img tag in a page whose final image it displays comes after a 302 redirect, is there a way with javascript to obtain what that final URL is after the redirect? Using javascript on img.src just gets the first URL (what's in the page), not what it was redirected to.
Here's a jsfiddle illustration: http://jsfiddle.net/jfriend00/Zp4zG/
No, this is not possible. src is an attribute and it does not change.
I know this question is old, and was already marked answered, but another question that I was trying to answer was marked as a duplicate of this, and I don't see any indication in any of the existing answers that you can get the true URL via the HTTP header. A simple example (assuming a single image tag on your page) would be something like this...
var req = new XMLHttpRequest();
req.onreadystatechange=function() {
if (req.readyState===4) {// && req.status===200) {
alert("actual url: " + req.responseURL);
}
}
req.open('GET', $('img').prop('src'), true);
req.send();
If you are open to using third party proxy this can be done. Obviously not a javascript solution This one uses the proxy service from cors-anywhere.herokuapp.com. Just adding this solution for people who are open to proxies and reluctant to implement this in backend.
Here is a fork of the original fiddle
$.ajaxPrefilter( function (options) {
if (options.crossDomain && jQuery.support.cors) {
var http = (window.location.protocol === 'http:' ? 'http:' : 'https:');
options.url = http + '//cors-anywhere.herokuapp.com/' + options.url;
//options.url = "http://cors.corsproxy.io/url=" + options.url;
}
});
$.ajax({
type: 'HEAD', //'GET'
url:document.getElementById("testImage").src,
success: function(data, textStatus, request){
alert(request.getResponseHeader('X-Final-Url'));
},
error: function (request, textStatus, errorThrown) {
alert(request.getResponseHeader('X-Final-Url'));
}
});
based on http://jsfiddle.net/jfriend00/Zp4zG, this snippets works in Firefox 17.0:
alert(document.getElementById("testImage").baseURI)
It doesn't work in Chrome. Not tested anything else-
Here is a workaround that I found out. But it works only if the image on the same domain otherwise you will get an empty string:
var img = document.getElementById("img");
getSrc(img.getAttribute("src"), function (realSrc) {
alert("Real src is: " + realSrc);
});
function getSrc(src, cb) {
var iframe = document.createElement("iframe"),
b = document.getElementsByTagName("body")[0];
iframe.src = src;
iframe.className = "hidden";
iframe.onload = function () {
var val;
try {
val = this.contentWindow.location.href;
} catch (e) {
val = "";
}
if (cb) {
cb(val);
}
b.removeChild(this);
};
b.appendChild(iframe);
}
http://jsfiddle.net/infous/53Layyhg/1/

Categories

Resources