Last active
September 18, 2016 20:53
-
-
Save rubiii/b117935cec88b08d35d35d7f71f37aae to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Takes a screenshot from a given Tweet. | |
// Usage: phantomjs twitter_screenshot.js https://twitter.com/Snowden/status/777557723118440448 | |
var system = require("system"), | |
args = system.args; | |
var url = args[1]; | |
if (!url) { | |
console.log("Please provide the URL to a Tweet."); | |
phantom.exit(1); | |
} | |
var resourceWait = 300, | |
maxRenderWait = 8000; | |
var page = require("webpage").create(), | |
count = 0, | |
renderTimeout; | |
page.viewportSize = { width: 1280, height: 1200 }; | |
function getTweetDimensions() { | |
return page.evaluate(function() { | |
var tweet = $(".permalink-tweet-container"), | |
offset = tweet.offset(); | |
return { | |
top: offset.top + 5, | |
left: offset.left + 5, | |
width: tweet.width() - 10, | |
height: tweet.height() - 10 | |
} | |
}); | |
} | |
function getFilename() { | |
var split = url.split("/"), | |
user = split[3], | |
id = split[5]; | |
return user + "_" + id + ".png"; | |
} | |
function screenshot() { | |
var filename = getFilename(); | |
page.clipRect = getTweetDimensions(); | |
page.render(filename); | |
console.log("Screenshot saved to " + filename); | |
phantom.exit(); | |
} | |
page.onResourceRequested = function(req) { | |
count += 1; | |
clearTimeout(renderTimeout); | |
}; | |
page.onResourceReceived = function(res) { | |
if (!res.stage || res.stage === "end") { | |
count -= 1; | |
if (count === 0) { | |
renderTimeout = setTimeout(function() { | |
console.log("All resources loaded."); | |
screenshot(); | |
}, resourceWait); | |
} | |
} | |
}; | |
console.log("Loading " + url); | |
page.open(url, function(status) { | |
if (status !== "success") { | |
console.log("Unable to load url. Status: " + status); | |
phantom.exit(1); | |
} else { | |
console.log("Waiting for resources to load."); | |
setTimeout(function() { | |
console.log("Timeout. Not all resources could be loaded."); | |
screenshot(); | |
}, maxRenderWait); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment