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
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 after effects bodymovin.js SVG animation with ID's on certain paths (image attached). I've put some css styles on these (cursor:pointer), which work fine but using jquery onClick for a redirect doesn't seem to be working. Any ideas why?
The animation itself is in an overlay which starts after a button is pressed.
The redirect code:
<script>
$(function() {
document.getElementById("replay").onclick = function () {
location.href = "www.yoursite.com";
};
});
</script>
The animation code:
<script>
$( ".animation" ).click(function() {
var anim;
var elem = document.getElementById('bodymovin_overlay')
var animData = {
container: elem,
renderer: 'svg',
loop: false,
autoplay: true,
rendererSettings: {
progressiveLoad:false
},
path: 'data_overlay.json'
};
anim = bodymovin.loadAnimation(animData);
});
</script>
Also the image is attached:
Remove # from document.getElementById("#replay").
Use document.getElementById("replay") (Native JS) or via jQuery $('#replay')
I believe the error occurs because you forgot to add a semi-colon.
var elem = document.getElementById('bodymovin_overlay')
to
var elem = document.getElementById('bodymovin_overlay');
Issue solved - the overlay was covering the animations z-index, had to give it a higher z-index than the overlay.
Final code that worked, hope it helps someone:
var lookingForLinks = true;
setTimeout(addLinksToSvgAnim, 1000);
function addLinksToSvgAnim() {
if (lookingForLinks) {
let medicalG = document.getElementById("medical");
let foodG = document.getElementById("food");
let collabG = document.getElementById("collab");
let volunteersG = document.getElementById("volunteers");
let projectsG = document.getElementById("projects");
let replayG = document.getElementById("replay");
if (medicalG && foodG && volunteersG && projectsG) {
lookingForLinks = false;
medicalG.addEventListener("click", function () {
window.location = window.location.protocol + "//" + window.location.hostname + "/medical-aid";
});
foodG.addEventListener("click", function () {
window.location = window.location.protocol + "//" + window.location.hostname + "/humanitarian-aid";
});
collabG.addEventListener("click", function () {
window.location = window.location.protocol + "//" + window.location.hostname + "/our-story/partners";
});
volunteersG.addEventListener("click", function () {
window.location = window.location.protocol + "//" + window.location.hostname + "/get-involved";
});
projectsG.addEventListener("click", function () {
window.location = window.location.protocol + "//" + window.location.hostname + "/bringhope-projects";
});
replayG.addEventListener("click", function () {
window.location = window.location.protocol + "//" + window.location.hostname + "/bringhope-projects";
});
}
setTimeout(addLinksToSvgAnim, 1000);
}
}
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"
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};
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);