Golang : Take screen shot of browser with JQuery example
In this tutorial, we will learn how to do a screen capture of a client(browser) and send the capture screen shot back to the web server to be saved as a PNG file and download into the client's computer afterward(need user permission).
This tutorial uses JQuery & JavaScript HTML renderer - html2canvas to capture the browser content either by targeting certain <div>
or entire page and pass the base64 data back to Golang web server.
This feature can be useful in situation where you want download a page screen shot at certain interval or use in tech support(with permission from client).
Here you go!
package main
import (
"bytes"
"encoding/base64"
"fmt"
"image"
"image/png"
"io/ioutil"
"net/http"
"os"
)
func SaveFile(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
imgBase64 := r.FormValue("data")
// remove "data:image/png;base64,"
imgBase64cleaned := imgBase64[len("data:image/png;base64,"):len(imgBase64)]
// decode base64 to buffer bytes
imgBytes, _ := base64.StdEncoding.DecodeString(imgBase64cleaned)
// convert []byte to image for saving to file
img, _, _ := image.Decode(bytes.NewReader(imgBytes))
imgFile, err := os.Create("./screen-capture.png")
if err != nil {
panic(err)
}
// save to file on your webserver
png.Encode(imgFile, img)
fmt.Println("screen-capture.png file saved")
}
// NOTE : For some odd reason this part has to be outside the r.Method == "POST"
// in order for the streaming/download straight to browser to work
streamBytes, _ := ioutil.ReadFile("./screen-capture.png")
//output to browser
w.Header().Set("Content-Disposition", "attachment; filename='screen-capture.png'")
w.Header().Set("Content-Type", "image/png")
w.Header().Set("Content-Transfer-Encoding", "binary")
w.Header().Set("Content-Description", "File Transfer")
//w.Header().Set("Content-Length", string(len(streamBytes)))
// will produce warning message : http: invalid Content-Length of "뚴"
// ok, pump it out to the browser!
b := bytes.NewBuffer(streamBytes)
if _, err := b.WriteTo(w); err != nil {
fmt.Fprintf(w, "%s", err)
}
}
func ScreenCapture(w http.ResponseWriter, r *http.Request) {
html := `<html><body>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.3.js"></script>
<script type="text/javascript" src="https://socketloop.com/public/tutorial/html2canvas.js"></script>
<style type="text/css">
#buttons-area
{
margin:30px auto;
padding:5px;
border:solid #cdcdcd 1px;
width:700px;
text-color:white;
background:#f4f4f4;
}
#target-area
{
margin:50px auto;
padding:15px;
border:solid #cdcdcd 1px;
width:700px;
background:blue;
}
button
{
text-align:center;
width:48%;
height:80px;
border:1px solid #c3d825;
font-family:Verdana, Geneva, sans-serif;
border-radius:3px;
background:#c3d825;
color:#355105;
text-shadow: 0 1pm #ecffba;
font-weight:bolder;
font-size:18px;
border-radius:10px;
}
</style>
<div id="target-area"></div>
<div id="buttons-area">
<h1>Take a screenshot with JQuery and Golang example.</h1>
<button type="button" onclick="captureDiv()">capture div and replace</button>
<button type="button" onclick="capturePage()">capture entire page & save</button>
</div>
</body></html>
<script type="text/javascript">
function captureDiv() {
html2canvas([document.getElementById('buttons-area')], {
onrendered: function(canvas)
{
var imgBase64 = canvas.toDataURL() // already base64
var img2html = '<img src=' + imgBase64 + '>'
document.getElementById('target-area').innerHTML = img2html;
}
});
}
function capturePage() {
html2canvas(document.body, {
onrendered: function(canvas)
{
var imgBase64 = canvas.toDataURL() // already base64
var img2html = '<img src=' + imgBase64 + '>'
// too big to fit into target-area div
// so, we save to file
//document.getElementById('target-area').innerHTML = img2html;
//post screen capture base64 image data to save function
$.post("/save", {data: imgBase64}, function () {
window.location.href = "save"});
}
});
}
</script>`
w.Write([]byte(html))
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/", ScreenCapture)
mux.HandleFunc("/save", SaveFile)
http.ListenAndServe(":8080", mux)
}
Hope this helps and happy coding!
References:
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+4.2k Javascript : How to show different content with noscript?
+21.6k Golang : Convert string slice to struct and access with reflect example
+5.9k Linux/MacOSX : Search for files by filename and extension with find command
+11.6k Golang : convert(cast) float to string
+6.8k Golang : Decode XML data from RSS feed
+29.7k Golang : Get and Set User-Agent examples
+12.6k Golang : zlib compress file example
+9.1k Golang : Create and shuffle deck of cards example
+5.6k Linux/Unix/PHP : Restart PHP-FPM
+17.2k Golang : Check if IP address is version 4 or 6
+10k Golang : Use regular expression to get all upper case or lower case characters example