Image upload with different sizes in different folders using Pluploader - javascript

I want to make simple upload using plupload which takes image and convert that to multiple size like thumb,medium,full and set to their different folders location,
I have tried the code for that which run well for uploading files to different location but can't resize the image for that particular folder.
It is storing all three files with same size.
Here what I have tried is:
My Code Is:
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://code.jquery.com/jquery-2.1.4.min.js" type="text/javascript"></script>
<script type="text/javascript" src="plupload.full.min.js"></script>
</head>
<body>
<div id="filelist">Your browser doesn't have Flash, Silverlight or HTML5 support.</div>
<br />
<div id="container">
<a id="pickfiles" href="javascript:;">[Select files]</a>
<a id="uploadfiles" href="javascript:;">[Upload files]</a>
</div>
<br />
<pre id="console"></pre>
<script type="text/javascript">
var folder = '';
var i = 0;
folder = 'full';
// Custom example logic
var uploader = new plupload.Uploader({
runtimes: 'html5,flash,silverlight,html4',
browse_button: 'pickfiles', // you can pass in id...
container: document.getElementById('container'), // ... or DOM Element itself
url: "http://localhost/plupload_new/public_html/upload.php?diretorio=" + folder,
filters: {
max_file_size: '10mb',
mime_types: [
{title: "Image files", extensions: "jpg,gif,png"},
{title: "Zip files", extensions: "zip"}
]
},
// Flash settings
flash_swf_url: '/plupload/js/Moxie.swf',
// Silverlight settings
silverlight_xap_url: '/plupload/js/Moxie.xap',
init: {
PostInit: function () {
document.getElementById('filelist').innerHTML = '';
document.getElementById('uploadfiles').onclick = function () {
uploader.start();
return false;
};
},
FilesAdded: function (up, files) {
plupload.each(files, function (file) {
document.getElementById('filelist').innerHTML += '<div id="' + file.id + '">' + file.name + ' (' + plupload.formatSize(file.size) + ') <b></b></div>';
});
},
UploadProgress: function (up, file) {
document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>";
},
Error: function (up, err) {
document.getElementById('console').innerHTML += "\nError #" + err.code + ": " + err.message;
}
}
});
var i = 1;
uploader.bind('BeforeUpload', function (up, file) {
if ('thumb' in file) {
if (i == 1) {
//thumb
up.settings.url = 'http://localhost/plupload_new/public_html/upload.php?diretorio=thumb',
up.settings.resize = {width: 50, height: 50, quality: 50};
} else {
// medium size
up.settings.url = 'http://localhost/plupload_new/public_html/upload.php?diretorio=medium',
up.settings.resize = {width: 400, height: 600, quality: 70};
}
} else {
up.settings.url = 'http://localhost/plupload_new/public_html/upload.php?diretorio=full',
up.settings.resize = {quality: 100};
}
uploader.bind('FileUploaded', function (up, file) {
if (!('thumb' in file)) {
file.thumb = true;
file.loaded = 0;
file.percent = 0;
file.status = plupload.QUEUED;
up.trigger("QueueChanged");
up.refresh();
} else {
i++;
file.medium = true;
file.loaded = 0;
file.percent = 0;
file.status = plupload.QUEUED;
up.trigger("QueueChanged");
up.refresh();
}
});
});
uploader.init();
</script>
</body>
</html>
Any help would be appreciated
Thank you in advance.

I have found the solution,which is a very small change to my code posted in question,the only thing i need to change is i have added attribute enabled:true in my resize parameter like,
up.settings.resize = {width: 80, height: 80, enabled: true};

Related

how to define a var from json to js?

I'm a newbie in javascript and need your help.
I don't know what to do and how to do to make this working:
I have the following js and html code:
var slides = '';
var slideImg = slider.images;
var i;
for (var i=0; i<slider.images.length; i++) {
slides += '<div id="slide'+i+'" class="slideEl" ><img src="'+slider.images[i].src+'"><div class="container-images">'+slider.images[i].CTA.text+'</div></div>';
}
document.getElementById('slides').innerHTML = slides;
document.getElementById('slides').style.width = window.innerWidth * (slideImg.length) + 'px';
document.getElementById('slides').style.transitionDuration = slideImg[0].speed + 's';
document.getElementById('slides').style.left = 0;
var indexSlide = 0;
function moveSlide(params) {
var slideWidth = document.getElementsByClassName('slideEl')[0].offsetWidth;
document.getElementById('slides').style.transitionDuration = slideImg[0].speed + 's';
var element = document.getElementById('slides');
var rect = element.getBoundingClientRect();
var newPos = rect.left;
if(params == 'right' && indexSlide < slideImg.length -1){
newPos -= slideWidth;
indexSlide++;
} else if (params == 'left' && indexSlide > 0) {
newPos += slideWidth;
indexSlide--;
}
document.getElementById('slides').style.transitionDuration = slider.images[indexSlide].speed + 's';
document.getElementById('slides').style.left = newPos + 'px';
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>JS exercise</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/png" href="media/favicon-32x32.png" />
<link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet">
<link rel="stylesheet" type="text/css" media="screen" href="css/style.css" />
</head>
<body>
<div id="slider">
<div id="slides" class="slides"></div>
<div class="container-slider">
<span id="arrowLeft" class="arrow" onclick="moveSlide('left')">〈</span>
<span id="arrowRight" class="arrow" onclick="moveSlide('right')">〉</span>
</div>
</div>
<footer>Copyright © 2019</footer>
<script language="javascript" src="js/script.js"></script>
<script type="text/javascript" src="js/data.json"></script>
</body>
</html>
and besides that, I have another file called data.json:
[{
"autoplay" : "yes",
"transition" : "slide",
"images" :[
{
"src" : "https://some-img.jpg",
"speed" : "1.5",
"CTA" : {
"text" : "Join Now",
"link" : "http://test.com",
"position" : "bottom-right"
}
},
{
"src" : "https://some-img.jpg",
"speed" : "1.5",
"CTA" : {
"text" : "Join Now",
"link" : "http://test.com",
"position" : "bottom-right"
}
},
{
"src" : "https://some-img.jpg",
"speed" : "1.5",
"CTA" : {
"text" : "Join Now",
"link" : "http://www.test.com",
"position" : "bottom-right"
}
}
]
}]
How can I get the slider var from json to javascript just to defined the length of the whole slider?
EDIT(from answer):
#Mrunmay Deswandikar, I've added this piece of code at the start of my script.js file:
var xhttp = new xmlhttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var data = JSON.parse(xmlhttp.responseText);
}
};
xhttp.open("GET", "http://wip.2mo.ro/sandra/js-slider/js/data.json", true);
xhttp.send();
var slides = '';
var slideImg = slider.images;
.....
I got this error: Uncaught ReferenceError: xmlhttpRequest is not defined
at script.js:1
(anonymous) # script.js:1
What am I missing?
Many thanks,
Sandra
Script tags are not meant to be used to load json data. Use fetch instead.
fetch('js/data.json')
.then(res=>res.json())
.then(data=>{
const slider = data.shift();
/** rest of your code here */
})
.catch(err=>{
console.log(err.message);
});
Fetch by default uses promises, but if you prefer to use it with async/await (syntaxical sugar for Promises).
async function loadData(){
const res = await fetch('/js/data.json');
const data = await res.json();
const slider = data.shift();
/** rest of code here */
}
loadData().catch(err=>console.log(err);
To get the data from json, use Ajax request to load JSON file.
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var data = JSON.parse(xmlhttp.responseText);
}
};
xhttp.open("GET", "data.json", true);
xhttp.send();
This will get all the data of data.json file, into variable data.
If your data.json file is located at the same directory, else you can use releative path, but best way will be use server path, like,
xhttp.open("GET","https://yourwebsite/DIRECTORY/data.json",true);

How do I upload video to server after previewed using phonegap

Pls I urge for assistance on how to upload video captured with phonegap android app. I could upload captured video, but I want the user of the app to watch the captured video before uploading it. That is where I'm having problem.
The code I am using is below:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href="css/jquery.mobile-1.2.0.min.css" />
<script src="js/jquery-1.8.2.min.js"></script>
<script src="js/jquery.mobile-1.2.0.min.js"></script>
<script src="js/modernizr-latest.js"></script>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript">
document.addEventListener("deviceready", init, false);
function init() {
document.querySelector("#takeVideo").addEventListener("touchend", function() {
alert("Take video");
navigator.device.capture.captureVideo(captureSuccess, captureError, {limit: 1, duration: 10});
}, false);
}
function captureError(e) {
console.log("capture error: "+JSON.stringify(e));
}
function captureSuccess(s) {
console.log("Success");
console.dir(s[0]);
var v = "<video controls='controls'>";
v += "<source src='" + s[0].fullPath + "' type='video/mp4'>";
v += "</video>";
document.querySelector("#videoArea").innerHTML = v;
}
function uploadFile(s) {
// Get URI of picture to upload
var img = document.getElementById('videoArea');
var mediaFile = img;
alert(mediaFile);
if (!mediaFile || (img.style.display == "none")) {
alert("Take picture or select picture from library first.");
return;
}
var ft = new FileTransfer(),
path = mediaFile.substr(mediaFile.lastIndexOf('/')+1),
name = mediaFile.name;
var options = new FileUploadOptions();
options.mimeType = "document";
options.fileName = name;
options.chunkedMode = true;
options.params = params;
ft.upload(path,
"http://www.example.com/folder/upload.php",
function(result) {
alert('Upload success: ' + result.responseCode);
alert(result.bytesSent + ' bytes sent');
},
function(error) {
alert('Error uploading file ' + path + ': ' + error.code);
},
options);
}
</script>
</head>
<body>
<button id="takeVideo">Take Video</button><br>
<b>Status:</b> <span id="camera_status"></span><br>
<div id="videoArea"></div>
<button type="submit" onclick="uploadFile();">Submit</button>
</body>
</html>
Pls I count on your assistance to solve this challenge. I do not know how to reference "video" tagname nor extract image path from the videoArea id of the div.

When using window.open(), $(document).ready does not fire in opened window

I'm opening a new window to display a report using javascript and jquery in an MVC 4 application. The code is as follows.
window.open method:
$(document).ready(function () {
// validation stuff
submitHandler: function (form) {
var brewery = document.getElementById('BrewerySelect').value;
var line = document.getElementById('LineSelect').value;
var day = document.getElementById('datepicker').value;
var width = window.innerWidth * 0.66;
var height = width * window.innerHeight / window.innerWidth;
var urlStr = '/DashboardReport/Report?brewery=' + brewery + '&line=' + line.trim() + '&day=' + day;
alert(urlStr);
window.open(urlStr, 'newwindow', 'width=' + width + ', height=' + height + ', top=' + ((window.innerHeight - height) / 2) + ', left=' + ((window.innerWidth - width) / 2));
}
});
});
The controller does nothing, which I have tried as both PartialViewResult and ActionResult, the rest of the methods in the controller work fine for the ajax calls. The report works in a modal.:
public ActionResult Report()
{
return View();
}
The page that is opened:
#{
Layout = null;
}
<html>
<head>
<title>Report</title>
<link href="~/Content/bootstrap.min.css" rel="stylesheet" type="text/css" />
<link href="~/Content/Site.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="reportBody" style="height: 100%;">
</div>
<script src="~/Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
<script src="~/Scripts/scripts.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
var brewery = GetURLParameter('brewery');
var line = GetURLParameter('line');
var day = GetURLParameter('day');
alert('document hit');
SetReport(brewery, line, day);
});
function GetURLParameter(sParam)
{
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++)
{
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam)
{
return sParameterName[1];
}
}
}​
function SetReport(brewery, line, day) {
var url = '#Url.Action("GetUrl")';
alert('SetReport Hit ( action url = ' + url + ')');
$.ajax({
url: url,
data: { breweryCode: brewery, packageLine: line, date: day },
dataType: 'json',
cache: false,
type: "POST",
success: function (data) {
alert('SetReport success. data = ' + data);
var url = '<iframe src="' + data + '" height="100%" width="100%" scrolling="auto"></iframe>';
$('#reportBody').html(url).show();
},
error: function (response) {
alert('document.ready() dashboardReportForm SetForm() method failed');
}
});
}
</script>
</body>
</html>
I've set alerts throughout the javascript to let me know what is getting hit, but none of the alerts are firing. The document.ready function is not being hit.
There's a U+200b character after the ending bracket of GetURLParameter function, which causes syntax error. Remove it and it should work.
See No visible cause for "Unexpected token ILLEGAL"

Multiple Image upload to server in Cordova

I tried uploading multiple Images to server.
I am able to click images and display it in block but not able to transfer it to server. Error I am getting is 04-02 10:35:41.984: I/chromium(23772): [INFO:CONSOLE(104)] "Uncaught TypeError: Cannot call method 'lastIndexOf' of undefined", source: file:///android_asset/www/index.html (104)
Code:
<!DOCTYPE html>
<html>
<head>
<title>Submit form</title>
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8">
var pictureSource; // picture source
var destinationType; // sets the format of returned value
// Wait for device API libraries to load
//
document.addEventListener("deviceready",onDeviceReady,false);
// device APIs are available
//
function onDeviceReady() {
pictureSource = navigator.camera.PictureSourceType;
destinationType = navigator.camera.DestinationType;
}
// Called when a photo is successfully retrieved
//
/* function onPhotoURISuccess(imageURI) {
// Show the selected image
var smallImage = document.getElementById('smallImage');
smallImage.style.display = 'block';
smallImage.src = imageURI;
}*/
function onPhotoDataSuccess1(imageData) {
var smallImage1 = document.getElementById('smallImage1');
smallImage1.style.display = 'block';
smallImage1.src = "data:image/jpeg;base64," + imageData;
}
function onPhotoDataSuccess2(imageData) {
var smallImage2 = document.getElementById('smallImage2');
smallImage2.style.display = 'block';
smallImage2.src = "data:image/jpeg;base64," + imageData;
}
function onPhotoDataSuccess3(imageData) {
var smallImage3 = document.getElementById('smallImage3');
smallImage3.style.display = 'block';
smallImage3.src = "data:image/jpeg;base64," + imageData;
}
function capturePhoto1() {
// Take picture using device camera and retrieve image as base64-encoded string
navigator.camera.getPicture(onPhotoDataSuccess1, onFail, { quality: 20,
destinationType: destinationType.DATA_URL,
});
}
function capturePhoto2() {
// Take picture using device camera and retrieve image as base64-encoded string
navigator.camera.getPicture(onPhotoDataSuccess2, onFail, { quality: 20,
destinationType: destinationType.DATA_URL,
});
}
function capturePhoto3() {
// Take picture using device camera and retrieve image as base64-encoded string
navigator.camera.getPicture(onPhotoDataSuccess3, onFail, { quality: 20,
destinationType: destinationType.DATA_URL,
});
}
// A button will call this function
/*
function getPhoto(source) {
// Retrieve image file location from specified source
navigator.camera.getPicture(onPhotoURISuccess, onFail, { quality: 20,
destinationType: destinationType.FILE_URI,
sourceType: source });
}*/
//selected photo URI is in the src attribute (we set this on getPhoto)
var imageURI1 = document.getElementById('smallImage1').getAttribute("src");
var imageURI2 = document.getElementById('smallImage2').getAttribute("src");
var imageURI3 = document.getElementById('smallImage3').getAttribute("src");
if (!imageURI1) {
alert('Please select an image first.');
return;
}
var items = [imageURI1,imageURI2,imageURI3];
$.each(items,function(){
uploadPhoto($(this));
});
function uploadPhoto(imageURI) {
//set upload options
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = imageURI.substr(imageURI.lastIndexOf('/')+1);
options.mimeType = "image/jpeg";
options.params = {
firstname: document.getElementById("firstname").value,
lastname: document.getElementById("lastname").value,
workplace: document.getElementById("workplace").value
}
var ft = new FileTransfer();
ft.upload(imageURI, encodeURI("http://www.xyz.co/AppData/upload.php"), win, fail, options);
}
// Called if something bad happens.
//
function onFail(message) {
console.log('Failed because: ' + message);
}
function win(r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
//alert("Response =" + r.response);
console.log("Sent = " + r.bytesSent);
}
function fail(error) {
alert("An error has occurred: Code = " + error.code);
console.log("upload error source " + error.source);
console.log("upload error target " + error.target);
}
</script>
</head>
<body>
<form id="regform">
<input type="button" onclick="capturePhoto1();" value="Capture Photo"><br>
<img style="display:none;width:60px;height:60px;" id="smallImage1" src="" />
<input type="button" onclick="capturePhoto2();" value="Capture Photo"><br>
<img style="display:none;width:60px;height:60px;" id="smallImage2" src="" />
<input type="button" onclick="capturePhoto3();" value="Capture Photo"><br>
<img style="display:none;width:60px;height:60px;" id="smallImage3" src="" />
First Name: <input type="text" id="firstname" name="firstname"><br>
Last Name: <input type="text" id="lastname" name="lastname"><br>
Work Place: <input type="text" id="workplace" name="workPlace"><br>
<input type="button" id="btnSubmit" value="Submit" onclick="uploadPhoto();">
</form>
</body>
</html>
I guess there's some problem in function uploadPhoto(). Foreach loop is not handling imageURI properly.
What can be the solution?
Please see if it help for you. your uploadPhoto function has the imageURI parameter but you are calling the uploadPhoto() function in button click without passing any parameter. your function should be
function intUpload(){
var imageURI1 = document.getElementById('smallImage1').getAttribute("src");
var imageURI2 = document.getElementById('smallImage2').getAttribute("src");
var imageURI3 = document.getElementById('smallImage3').getAttribute("src");
if (!imageURI1) {
alert('Please select an image first.');
return;
}
var items = [imageURI1,imageURI2,imageURI3];
$.each(items,function(){
uploadPhoto($(this));
});
}
function uploadPhoto(imageURI) {
//set upload options
var d = new Date();
var options = new FileUploadOptions();
options.fileKey = "vImage" + d.getTime();
options.fileName = imageURI.substr(imageURI.lastIndexOf('/')+1);
options.mimeType = "image/jpeg";
options.params = {
firstname: document.getElementById("firstname").value,
lastname: document.getElementById("lastname").value,
workplace: document.getElementById("workplace").value
};
options.chunkedMode = false;
var ft = new FileTransfer();
ft.upload(imageURI, encodeURI("http://www.xyz.co/AppData/upload.php"), win, fail, options);
}
and your button click should be
<input type="button" id="btnSubmit" value="Submit" onclick="intUpload();">
also your html page doesn't include any jquery file but you are using $.each jquery function. please include the jquery file
<script type="text/javascript" charset="utf-8">
///// photo for 1 photo
var pictureSource; // picture source
var destinationType; // sets the format of returned value
// Wait for device API libraries to load
//
document.addEventListener("deviceready",onDeviceReady,false);
// device APIs are available
//
function onDeviceReady()
{
pictureSource=navigator.camera.PictureSourceType;
destinationType=navigator.camera.DestinationType;
}
// Called when a photo is successfully retrieved
var x=0;
function onPhotoDataSuccess(imageURI)
{
x++;
// Uncomment to view the base64-encoded image data
console.log(imageURI);
// Get image handle
//
var y = 'smallImage'+x;
var smallImage = document.getElementById(y);
smallImage.src = "data:image/jpeg;base64," + imageURI;
// Unhide image elements
//
smallImage.style.display = 'block';
// Show the captured photo
// The in-line CSS rules are used to resize the image
//
//var fso=new ActiveXObject("Scripting.FileSystemObject");
//fso.CopyFile("data:image/jpeg;base64," + imageURI,"file:///storage/sdcard/DCIM/");
}
// Called when a photo is successfully retrieved
//
function onPhotoURISuccess(imageURI)
{
x++;
// Uncomment to view the base64-encoded image data
console.log(imageURI);
//alert(imageURI);
// Get image handle
//
var y = 'smallImage'+x;
var smallImage = document.getElementById(y);
//alert(smallImage);
smallImage.src = imageURI;
// Unhide image elements
//
smallImage.style.display = 'block';
//alert(smallImage.src)
}
// A button will call this function
//
function capturePhoto()
{
// Take picture using device camera and retrieve image as base64-encoded string
navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 50,
destinationType: destinationType.DATA_URL });
}
// A button will call this function
//
function capturePhotoEdit()
{
// Take picture using device camera, allow edit, and retrieve image as base64-encoded string
navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 20, allowEdit: true,
destinationType: destinationType.DATA_URL });
}
// A button will call this function
//
function getPhoto()
{
// Retrieve image file location from specified source
navigator.camera.getPicture(onPhotoDataSuccess, onFail, {
quality: 50,
allowEdit: true,
destinationType: Camera.DestinationType.DATA_URL,
sourceType: Camera.PictureSourceType.SAVEDPHOTOALBUM
});
/* window.imagePicker.getPictures(
function(results) {
for (var i = 0; i < results.length; i++) {
console.log('Image URI: ' + results[i]);
alert('Image URI: ' + results[i]);
}
}, function (error) {
console.log('Error: ' + error);
}, {
maximumImagesCount: 4,
width: 800
}*/
}
// Called if something bad happens.
//
function onFail(message)
{
alert('Failed because: ' + message);
}
</script>

javascript pass current url as parameter instead of data from textbox

I need to pass the url where the javascript is at the moment instead of using the url in the textbox.
Currently I have textbox and a button, I am getting the url from the textbox and then using it in the javascript. I want only to press the button and the script to get automatically the page where the code is. For example, if I have the code at www.mypage.com, I want when I'll click the button the javascript to get the url automatically and play with it.
Here is the complete code I am using:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript" src="External/base64.js"></script>
<script type="text/javascript" src="External/canvas2image.js"></script>
<script type="text/javascript" src="External/jquery-1.6.2.min.js"></script>
<script type="text/javascript" src="build/html2canvas.js?221"></script>
<script type="text/javascript" src="build/jquery.plugin.html2canvas.js"></script>
<script type="text/javascript" src="http://www.hertzen.com/js/ganalytics-heatmap.js"></script>
<script type="text/javascript">
var date = new Date();
var message,
timeoutTimer,
timer;
var proxyUrl = "http://html2canvas.appspot.com";
function addRow(table, field, val) {
var tr = $('<tr />').appendTo($(table));
tr.append($('<td />').css('font-weight', 'bold').text(field)).append($('<td />').text(val));
}
function throwMessage(msg, duration) {
window.clearTimeout(timeoutTimer);
timeoutTimer = window.setTimeout(function () {
message.fadeOut(function () {
message.remove();
});
}, duration || 2000);
$(message).remove();
message = $('<div />').html(msg).css({
margin: 0,
padding: 10,
background: "#000",
opacity: 0.7,
position: "fixed",
top: 10,
right: 10,
fontFamily: 'Tahoma',
color: '#fff',
fontSize: 12,
borderRadius: 12,
width: 'auto',
height: 'auto',
textAlign: 'center',
textDecoration: 'none'
}).hide().fadeIn().appendTo('body');
}
$(function () {
$('ul li a').click(function (e) {
e.preventDefault();
$('#url').val(this.href);
$('button').click();
})
var iframe, d;
$('input[type="button"]').click(function () {
$(iframe.contentWindow).unbind('load');
$(iframe).contents().find('body').html2canvas({
canvasHeight: d.body.scrollHeight,
canvasWidth: d.body.scrollWidth,
logging: true
});
});
$('button').click(function () {
$(this).prop('disabled', true);
var url = $('#url').val();
$('#content').append($('<img />').attr('src', 'loading.gif').css('margin-top', 40));
var urlParts = document.createElement('a');
urlParts.href = url;
$.ajax({
data: {
xhr2: false,
url: urlParts.href
},
url: proxyUrl,
dataType: "jsonp",
success: function (html) {
iframe = document.createElement('iframe');
$(iframe).css({
'visibility': 'hidden'
}).width($(window).width()).height($(window).height());
$('#content').append(iframe);
d = iframe.contentWindow.document;
d.open();
$(iframe.contentWindow).load(function () {
timer = date.getTime();
$(iframe).contents().find('body').html2canvas({
canvasHeight: d.body.scrollHeight,
canvasWidth: d.body.scrollWidth,
logging: true,
proxyUrl: proxyUrl,
logger: function (msg) {
$('#logger').val(function (e, i) {
return i + "\n" + msg;
});
},
ready: function (renderer) {
$('button').prop('disabled', false);
$("#content").empty();
var finishTime = new Date();
var table = $('<table />');
$('#content')
.append('<h2>Screenshot</h2>')
.append(renderer.canvas)
.append(table);
Canvas2Image.saveAsJPEG(renderer.canvas);
}
});
});
$('base').attr('href', urlParts.protocol + "//" + urlParts.hostname + "/");
html = html.replace("<head>", "<head><base href='" + urlParts.protocol + "//" + urlParts.hostname + "/' />");
if ($("#disablejs").prop('checked')) {
html = html.replace(/\<script/gi, "<!--<script");
html = html.replace(/\<\/script\>/gi, "<\/script>-->");
}
// console.log(html);
d.write(html);
d.close();
}
});
});
});
</script>
<base />
</head>
<body>
<div style="float:left;width:500px;">
<label for="url">Website URL:</label>
<input type="url" id="url" value="http://www.google.com" /><button>Get screenshot!</button>
<!-- <input type="button" value="Try anyway" />--><br />
</div>
<div style="clear:both;"></div>
<div id="content"></div>
</body>
</html>
Thanks in advance, Laziale
To pass the current URL as a parameter, you should be able to use any of the following ways to get the current URL:
document.URL
window.location
window.location.href
To use the current URL as opposed to the textbox value, change the following in your $('button').click() event:
var url = $('#url').val();
to:
var url = document.URL; //or any of the other suggestions

Categories