Bit of a long shot, but is there a javascript function/process which allows automatically takes a screenshot of a specified area, and outputs a picture to a folder on my computer. Ideally, it would be able to put within a loop so that it takes a picture for each loop iteration.
Is this at all remotely possible?
If you have a web server with PHP installed, you can simulate this using wkhtmltoimage. To generate a new file every 5 seconds, your JS would be:
$(document).ready(function() {
function takeImage() {
$.post(
'htmltoimage.php',
{ currentUrl : window.location + "?stopTimer=1" }, // data that your script might need
function(data) {
if (data.url !== undefined) {
console.log("The URL where you can download your image is " + data.url);
}
},
'json' // use JSON for expected return type
);
}
var startTimer = <?php echo (isset($_POST['stopTimer']) ? "false" : "true"); ?>
if (startTimer) { setTimeout(takeImage, 5000); }
});
Your PHP file would simply use wkhtmltoimage to go to your URL. In its most simple form:
<?php
function() {
$outputLocation = "/images/output_" . strtotime(date()) . ".png";
// assuming wkhtmltoimage is in your PATH (otherwise specify full path to executable below)
`wkhtmltoimage $_POST['currentUrl'] $outputLocation`;
return array('url' => $outputLocation);
}
?>
You can then crop it at the positions you desire using ImageMagick or a similar PHP image processing library.
This can also be achieved using Adobe AIR, or really any program that uses WebKit.
Yes, you can. There is a useful library for that. You might want to take a look:
http://phantomjs.org/screen-capture.html
Since PhantomJS is using WebKit, a real layout and rendering engine,
it can capture a web page as a screenshot. Because PhantomJS can
render anything on the web page, it can be used to convert contents
not only in HTML and CSS, but also SVG and Canvas.
Hope it helps.
Related
I am trying to get the HTML (ie what you see initially when the page completes loading) for some web-page URI. Stripping out all error checking and assuming static HTML, it's a single line of code:
function GetDisplayedHTML($uri) {
return file_get_contents($uri);
}
This works fine for static HTML, and is easy to extend by simple parsing, if the page has static file dependencies/references. So tags like <script src="XXX">, <a href="XXX">, <img src="XXX">, and CSS, can also be detected and the dependencies returned in an array, if they matter.
But what about web pages where the HTML is dynamically created using events/AJAX? For example suppose the HTML for the web page is just a brief AJAX-based or OnLoad script that builds the visible web page? Then parsing alone won't work.
I guess what I need is a way from within PHP, to open and render the http response (ie the HTML we get at first) via some javascript engine or browser, and once it 'stabilises', capture the HTML (or static DOM?) that's now present, which will be what the user's actually seeing.
Since such a webpage could continually change itself, I'd have to define "stable" (OnLoad or after X seconds?). I also don't need to capture any timer or async event states (ie "things set in motion that might cause web page updates at some future time"). I only need enough of the DOM to represent the static appearance the user could see, at that time.
What would I need to do, to achieve this programmatically in PHP?
To render page with JS you need to use some browser. PhantomJS was created for tasks like this. Here is simple script to run with Phantom:
var webPage = require('webpage');
var page = webPage.create();
var system = require('system');
var args = system.args;
if (args.length === 1) {
console.log('First argument must be page URL!');
} else {
page.open(args[1], function (status) {
window.setTimeout(function () { //Wait for scripts to run
var content = page.content;
console.log(content);
phantom.exit();
}, 500);
});
}
It returns resulting HTML to console output.
You can run it from console like this:
./phantomjs.exe render.js http://yandex.ru
Or you can use PHP to run it:
<?php
$path = dirname(__FILE__);
$html = shell_exec($path . DIRECTORY_SEPARATOR . 'phantomjs.exe render.js http://phantomjs.org/');
echo htmlspecialchars($html);
My PHP code assumes that PhantomJS executable is in the same directory as PHP script.
i'm trying to change a js file location when a visitor shows the source-code
, depending on that :
javascript functions don't work when the visitor shows the source-code
.
my idea is creating a file , put a javascript code to delete the file , in this situation the file won't be deleted if someone showed the source-code :
$check="$ip-$views-$id";
fopen("$check.txt","w"); //CREATING A FILE
// DELETING THE FILE ABOVE BY JAVASCRIPT , IT WON'T BE DELETED IF SOMEONE ENTERED VIA THE SOURCE-CODE MODE
?>
<div id="countno"></div>
<script type="text/javascript">
$('#countno').load('del.php?name=<?echo $check;?>&location=' + ' #countno');
</script>
<?
if (file_exists("$check.txt")) { //IF SOMEONE SHOWED THE SOURCE CODE
$new_location="fake_location.js";
}
else{
$new_location=$old_location;
}
?>
<script src="<?echo $new_location;?>"></script>
the problem now , is that the file_exists php function shows that the file still exists even though it was already deleted by the javascript code .
the file_exists function was executed before the javascript code !
any help / solution to make that php function check the file after that javascript code ? i know it's kinda impossible but it worth it !
What you are describing is not possible. php is a server side language while javascript is a client side language. Thus, the PHP on your page will always execute before the Javascript on your page executes. There is no way to make your Javascript execute first when you have it this way.
Instead, what you could do is to separate the PHP and Javascript. Have your file_exists check in another page. e.g. check.php.
if (file_exists("$check.txt")) {
echo "fake_location.js";
} else {
echo $old_location;
}
Then use an ajax call to make a request to check.php, and load your other script depending on what check.php outputs.
<script>
$.ajax({
method: "GET",
url: "check.php"
})
.done(function(script) {
$("#check").attr("src", script);
});
</script>
<script id="check"></script>
However, if your goal is to prevent people from figuring out where your javascript is located, it is not possible. Most browsers nowadays can inspect the HTML as it changes. They can see the loaded script without having to load the source separately.
I would like to change (or add if it doesn't exist) to a PDF file with multiple pages the setting that will force the PDF to be opened in two page mode (PageLayout : TwoPageLeft for example).
I tried with that kind of JavaScript (given with Enfocus FullSwitch as example) :
if(($error == null) && ($doc != null))
{
try
{
$outfile = $outfolder + '/' + $filename + ".pdf";
$doc.layout = "TwoPageLeft";
$doc.saveAs( {cPath : $outfile, bCopy : true});
$outfiles.push($outfile);
}
catch(theError)
{
$error = theError;
$doc.closeDoc( {bNoSave : true} );
}
}
But it doesn't work as I would like (it will be opened with Acrobat Pro and saved as a new file without including the setting about the layout).
Does anyone can help me to correct that code to let JS open the PDF file, set the layout inside the PDF datas and save it out?
The readable information inside the PDF file should looks like this:
PageLayout/TwoPageLeft/Type/Catalog/ViewerPreferences
For information, I'm using FullSwitch (Enfocus) to handle files in a workflow, with Acrobat Pro, and at this time, it's only saving the file without adding the setting.
I can't find myself the answer over all the Web I searched recently, so I askā¦
Thanks in advance!
I think you copied the "this.layout = ..." line out of the Acrobat JavaScript reference documentation, correct?
When you write a JavaScript for Switch to execute (or rather for Switch to instruct Acrobat to execute for you), you should use the "$doc" variable to refer to the document Switch is processing.
So try changing the line:
$this.layout = "TwoColumnLeft";
to
$doc.layout = "TwoColumnLeft";
As you say the rest of the code works and the document is saved without errors I assume the rest of your code is correct. The change proposed here will make the adjustment in the document you're looking for.
This is similar to: How to open a file using JavaScript?
Goal: to retrieve/open a file on an image's double click
function getFile(filename){
// setting mime this way is for example only
var mime = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
jQuery.ajax({ url : 'get_file.pl',
data : {filename:filename},
success : function(data){
var win = window.open('','title');
win.document.open(mime);
win.document.write(data);
win.document.close();
}
});
}
jQuery('#imgID').dblclick(function(){
getFile('someFile.docx');
});
I'm doing this off the top of my head, but I think the above would work for text files, but not binary. Is there a plugin that does this properly? The ideal would be to open the file in the browser (or application), rather than download, but I doubt that is a dream. If the file must be downloaded with the save/open dialog, that's fine.
Edit:
One piece of information that I forgot to mention is that I'd like this to be a POST request. This is partly why I was looking at AJAX to begin with. I've seen workarounds that have created forms/iframes to do something similar, but I was looking for a better handler of the returned info.
Seems to me there's no reason to do this via AJAX. Just open the new window to get_file.pl?filename=... and let the browser handle it. If the user has a plugin capable of handling the Content-Type sent by get_file.pl, the file will display; otherwise, it should download like any other file.
function getFile(filename) {
window.open('get_file.pl?filename=' + filename,'title');
}
jQuery('#imgID').dblclick(function() {
getFile('someFile.docx');
});
Edit: If you want to POST to your script, you can do it with some <form> hackery:
function getFile(filename) {
var win = 'w' + Math.floor(Math.random() * 10000000000000);
window.open('', win,'width=250,height=100');
var f = $('<form></form>')
.attr({target: win, method:'post', action: 'get_file.pl'})
.appendTo(document.body);
var i = $('<input>')
.attr({type:'hidden',name:'filename',value:filename})
.appendTo(f);
f[0].submit();
f.remove();
}
Of course, this is somewhat silly since it is impossible to hide your data from "prying eyes" with developer tools. If your filename really is sensitive, issue access tokens to the client, and look up the data in your sever script.
I'm using Andrew Valums' Ajax Upload plugin (GitHub link). Here is some code from it:
qq.getUniqueId = (function(){
var id = 0;
return function(){ return id++; };
})();
It's kind of a long story, but I'm in a situation where, under certain circumstances, I'd like the qq.getUniqueId function to start with an ID other than 0. It can still increment by one; it just has to start with something other than 0. What's the best way to do that?
Here are the steps to create a test environment:
Download the plugin: http://github.com/valums/file-uploader/zipball/master
Unzip it and move the "client" folder onto a web server.
Open the "demo.htm" file in a text editor, search for action: 'do-nothing.htm', and add onComplete: function(id, fileName, responseJSON) {alert(id)}, right after that.
Open the "demo.htm" file in a web browser. Be sure to access it through a web server (as opposed to just opening the local file) or else it won't work.
Upload a file. It should alert a "0" after the upload finishes. See if you can modify it so that I can pass in a different starting number.
Thanks!
Try replacing the function with one that calls the original, but adds an offset:
function offsetUniqueId(n) {
var old = qq.getUniqueId;
qq.getUniqueId = function() {
return old() + n;
}
}
See http://jsfiddle.net/alnitak/gWjqX/