Skip to content

Instantly share code, notes, and snippets.

@vperezb
Last active March 29, 2020 16:55
Show Gist options
  • Select an option

  • Save vperezb/c3b4a223c15c74dde0240f927b9254a1 to your computer and use it in GitHub Desktop.

Select an option

Save vperezb/c3b4a223c15c74dde0240f927b9254a1 to your computer and use it in GitHub Desktop.
Create a QR using Google Infographic API in JS
function generateQR(placeholderImageId) {
// For any support contact me on https://www.linkedin.com/in/vperezb-/ or https://www.malt.es/profile/victorperezberruezo
// Define your final url, the one where the user will arrive
var finalURL = 'https://www.tiendeo.com?utm_source=tiendeo?utm_medium=qr_post';
// Encode this url
var finalURLEncoded = encodeURIComponent(finalURL);
// Define the other variables (the ones you want to have in the redirector in order to
var identifyer = 'medium_post';
var version = 'first_version';
// Define the url where the redirector is hosted
var URLToCreateQR = 'http://my.domainn/redirector.html';
// Add to the redirector url the params you want to recieve and the final url encoded to allow the redirection
URLToCreateQR = URLToCreateQR + `?i=${identifyer}&v=${version}&u=${finalURLEncoded}`;
// Encode now the URL with the parameters and the final url encoded in order to keep those params while quering Google API
// https://developers.google.com/chart/infographics/docs/qr_codes
var URLToCreateQREncoded = encodeURIComponent(URLToCreateQR);
// Define the size of the QR
var width = 200
var height = 200
// Construct the request to be sent to Google API
var URLToRequest = `https://chart.googleapis.com/chart?cht=qr&chs=${width}x${height}&chl=` + URLToCreateQREncoded;
// Fetch the request and retrieve the image blob
fetch(URLToRequest)
.then(res => {
return res.blob()
})
.then(blob => {
// Create a URL for the response blob
var img = URL.createObjectURL(blob);
// Use the url to change the src attribute to a placeholder image object on your html code
document.getElementById(placeholderImageId).setAttribute('src', img);
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment