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
+6k Apt-get to install and uninstall Golang
+5.1k Golang : Get FX sentiment from website example
+4.4k MariaDB/MySQL : How to get version information
+11.8k Golang : Pagination with go-paginator configuration example
+15.7k Golang : How to reverse elements order in map ?
+38.8k Golang : How to read CSV file
+5.7k Golang : Generate multiplication table from an integer example
+11.1k Golang : Concatenate (combine) buffer data example
+7.1k Golang : How to convert strange string to JSON with json.MarshalIndent
+5.6k Cash Flow : 50 days to pay your credit card debt
+9k Golang : How to control fmt or log print format?
+11.5k Golang : Verify Linux user password again before executing a program example