I am working on one project and I am using JavaScript code to get a screenshot of the website.
The screenshot is working fine and is rendered nicely on the page.
What I want to do is instead of displaying it on the page, I want to show the 'save as' popup window with the screenshot.
Here is the current code which displays the image on the page:
<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('<h3>Details</h3>')
.append(table);
addRow(table,"Creation time",((finishTime.getTime()-timer)/1000) + " seconds");
addRow(table,"Total draws", renderer.numDraws);
addRow(table,"Context stacks", renderer.contextStacks.length);
addRow(table,"Loaded images", renderer.images.length/2);
addRow(table,"Performed z-index reorder", renderer.needReorder);
addRow(table,"Used rangeBounds", renderer.support.rangeBounds);
throwMessage('Screenshot created in '+ ((finishTime.getTime()-timer)/1000) + " seconds<br />Total of "+renderer.numDraws+" draws performed",4000);
}
});
});
$('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>
For that you can use canvas2image.
I guess you could put in your ready function:
ready: function(renderer) {
....
Canvas2Image.saveAsPNG(renderer.canvas);
Related
I have a button in my page to generate PDF I use JSPDF to perform the task, my problem is that I have to retrieve the content in other pages ... I retrieve the html in string format and I do not Know how to handle it....
any ideas
Thank you
jQuery(document).ready(function () {
var inner_content1;
var page_title = "ExternalPage";
$.ajax({
url: "https://site.sharepoint.com/sites/sites/site/_api/web/Lists/getbytitle('Pages')/items?$filter=Title eq '" + page_title +"'",
type: "GET",
headers: {
"ACCEPT": "application/json;odata=verbose"
},
success: function (data) {
if (data.d.results[0]) {
inner_content1 = data.d.results [0].HtmlContenu;
str = "<div id='someID'>" + inner_content1 + "<div/>";
//alert(inner_content.replace(/(<([^>]+)>) /ig,""));
html = $.parseHTML( str ),
nodeNames = [];
//var $newDiv = $("<div/>") // creates a div element
//.attr("id", "someID"); // adds the id
//$(html).append($newDiv);
jQuery(document).ready(function () {
var doc = new jsPDF();
var specialElementHandlers = {
'#someID': function (element, renderer) {
return true;
}
};
$('#cmd').click(function () {
doc.fromHTML($("#someID").get(0), 15, 15, {
'width': 170,
'elementHandlers': specialElementHandlers
});
doc.save('sample-file.pdf');
});
});
}
},
error: function(){ //Error }
}});
});
I have a script ajax which is launched every 32 seconds sending an ajax request :
setInterval(function() {
var dt = new Date();
var time = dt.getHours() + ":" + dt.getMinutes() + ":" + dt.getSeconds();
console.time("debut ajax");
$.getJSON('http://127.0.0.1:<?php echo $_SERVER['SERVER_PORT']; ?>/order/get_orders', function(data) {
//console.log(data);
if(jQuery.type(data) === "array") {
var id = data[0].id; var starter = data[0].starter; var meal = data[0].meal; var dessert = data[0].dessert; var expenses = data[0].expenses;
var iduser = data[0].log_by; var date = data[0].date;
var server= "<?php echo $this->config->item('server_url'); ?>index.php/account/updateExternal?";
$.ajax({
url: server+"&callback=?",
data: "balance="+expenses+"&starter="+starter+"&meal="+meal+"&dessert="+dessert+"&date="+date+"&id_user="+iduser+"&place=client2",
type: 'POST',
success: function (resp) {
var myObj = $.parseJSON(resp);
$.getJSON("http://127.0.0.1:<?php echo $_SERVER['SERVER_PORT']; ?>/order/update_log?id="+id+"&balance="+myObj.expenses+"&starter="+myObj.starter+"&meal="+myObj.meal+"&dessert="+myObj.dessert+"&id_user="+myObj.id_user, function(data) {
});
},
error: function(e) {
//alert('Error: '+e);
}
});
}
});
console.timeEnd("fin ajax");
}, 32 * 1000);
During this ajax request I need to prevent or stop the page from refreshing. How to do it ?
// Reload the page if the input is onfocusout for some reasons
$(document).ready(function(){
$(function(){
$("#barcode").focus();
$('#mtsg').html('Staff Canteen Software<br />Veuillez placer votre badge pour identification');
});
$( "#barcode" ).focusout(function() {
$(location).attr('href', "http://127.0.0.1:<?php echo $_SERVER['SERVER_PORT']; ?>/");
});
});
///
I have three separate javascript/jquery functions, all of which fire off after the user clicks a button. One function posts to a form handler. Another function creates a new tab. And the third function grabs the id of the new tab and posts sends new information into the tab via an ajax call. They all work together and depend on one another.
I have tried many different configurations, and I cannot figure out how to properly get a confirmation dialog (e.g., "Do you want to perform this action?) to work with all three of these simultaneously. If the user clicks "yes," the process should fire. If the user clicks "no," the process should die. Any help is greatly appreciated.
Edit: I've posted my code below. I'm sure it's really noobish, which is why I didn't post it the begin with. Trying to learn though. Thanks!
jQuery(".update_form").click(function(e) { // changed
e.preventDefault();
jQuery.ajax({
type: "POST",
url: "/eemcontrolpanel/process.cshtml",
data: jQuery(this).parent().serialize() // changed
});
return false; // avoid to execute the actual submit of the form.
});
jQuery(".update_form").click(function () {
var form = jQuery(this).parents('form:first');
title = jQuery("input[name='process']", form).val();
$('#tt').tabs('add',{
title:title,
content:'Script starting',
closable:true
});
$('div.panel-body:last').attr("id","tab" + panelIds[panelIds.length - 1] + 1);
panelIds.push(panelIds[panelIds.length - 1] + 1);
});
jQuery(".update_form").click(function (e) {
e.preventDefault();
//var j = jQuery.noConflict();
var form = jQuery(this).parents('form:first');
var fileName = jQuery("input[name='process']", form).val();
jQuery(document).ready(function () {
var XHR;
var stopMe = 1;
var isSame = 0;
var oldhtml;
var tabID = "tab" + panelIds[panelIds.length - 1];
jQuery("#"+ tabID).everyTime(1000, function (i) {
if (stopMe != 2){
XHR = jQuery.ajax({
url: "/eemcontrolpanel/jobs/" + fileName + ".txt",
cache: false,
success: function (html){
if (html === oldhtml){
isSame++;
if (isSame === 10){
stopMe = 2;
}
}
jQuery("#"+ tabID).html("<pre>" + html + "</pre>").scrollHeight;
oldhtml = html;
}
});
} else {
jQuery("#"+ tabID).stopTime();
}
jQuery("#"+ tabID).css({ color: "white" });
});
});
});
This is what I ended up doing. I basically combined all the functions into one big function.
var panelIds = new Array();
panelIds.push('0');
jQuery(".update_form").click(function (e) {
if (confirm('Are you sure?')) {
e.preventDefault();
jQuery.ajax({
type: "POST",
url: "/eemcontrolpanel/process.cshtml",
data: jQuery(this).parent().serialize() // changed
});
var form = jQuery(this).parents('form:first');
var title = jQuery("input[name='process']", form).val();
$('#tt').tabs('add',{
title:title,
content:'Script starting',
closable:true
});
$('div.panel-body:last').attr("id","tab" + panelIds[panelIds.length - 1] + 1);
panelIds.push(panelIds[panelIds.length - 1] + 1);
//var j = jQuery.noConflict();
var fileName = jQuery("input[name='process']", form).val();
var XHR;
var stopMe = 1;
var isSame = 0;
var oldhtml;
var tabID = "tab" + panelIds[panelIds.length - 1];
//alert(tabID);
jQuery("#"+ tabID).everyTime(1000, function (i) {
//alert(stopMe);
//add also if stopme=false else quit/end/whatever
if (stopMe != 2){
//alert(stopMe);
XHR = jQuery.ajax({
url: "/eemcontrolpanel/jobs/" + fileName + ".txt",
cache: false,
success: function (html){
//alert(html);
if (html === oldhtml){
isSame++;
//alert(isSame);
if (isSame === 10){
stopMe = 2;
//alert(stopMe);
}
}
jQuery("#"+ tabID).html("<pre>" + html + "</pre>").scrollHeight;
oldhtml = html;
//alert(oldhtml);
}
});
} else {
jQuery("#"+ tabID).stopTime();
}
jQuery("#"+ tabID).css({ color: "white" });
});
} else {
return false;
}
});
Have you tried this:
Function onButtonPush(){
if(confirm('confirm message')){
function1();
function2();
function3();
}
}
I'm using mmenu library in jquery mobile, when parsing an xml and append the result to:
<nav></nav>
the sub-menus don't work correctly.
here is my js:
<script>
$(document).ready(function(){
$.ajax({
type: "GET",
url: "MainMenuAsXml.xml",
dataType: "xml",
cache: false,
success: function(xml){
var list_elem = $("<ul></ul>");
$(xml).find('module').each(function(){
var module = $(this);
var moduleLabel = module.attr("text");
var directories_list = $("<li class='Selected'></li>").appendTo(list_elem);
module.find("directory").each(function(){
var directory = $(this);
var directoryLabel = directory.attr("text");
var directory_elem = $("<li></li>").append("<span>" + directoryLabel + "</span>").appendTo(directories_list);
var entries_list = $("<ul></ul>").appendTo(directory_elem);
directory.find("entries").each(function(){
var entries = $(this);
var linkName = entries.attr("text");
var myLink = entries.attr("link");
$('<li>' + linkName + '</li>' ).appendTo(entries_list);
});
});
});
$("#menu-left").append(list_elem));
buildMenu();
},
error: function() {
alert("An error occurred while processing XML file.");
}
});
});
</script>
I'm sure that the parsing result is correct but I think there is an error using the function.
and here is the output
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