Add methods to Chrome Browser Console - javascript

I found a method which can create files from browser console in Chrome. I want to add this function to browsers defaults methods so that, next time I want to use that function, I dont need to paste that function and work with it again. I use this multiple times a day. Like 60 - 100 times.
Is there any way to add this function to chrome? I want this load each time I open the browser.
(function(console){
console.save = function(data, filename){
if(!data) {
console.error('Console.save: No data')
return;
}
if(!filename) filename = 'console.json'
if(typeof data === "object"){
data = JSON.stringify(data, undefined, 4)
}
var blob = new Blob([data], {type: 'text/json'}),
e = document.createEvent('MouseEvents'),
a = document.createElement('a')
a.download = filename
a.href = window.URL.createObjectURL(blob)
a.dataset.downloadurl = ['text/json', a.download, a.href].join(':')
e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
a.dispatchEvent(e)
}
})(console)

As Barmar told, bookmarlet helped me.
I am adding full code for reference.
javascript:void((function(d){var e=d.createElement('script');e.innerHTML="
(function(console){
console.save = function(data, filename){
if(!data) {
console.error('Console.save: No data');
return 0;
}
if(!filename)
filename = 'console.json';
if(typeof data === \"object\"){
data = JSON.stringify(data, undefined, 4);
}
var blob = new Blob([data], {type: 'text/json'}),
e = document.createEvent('MouseEvents'),
a = document.createElement('a');
a.download = filename;
a.href = window.URL.createObjectURL(blob);
a.dataset.downloadurl = ['text/json', a.download, a.href].join(':');
e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
a.dispatchEvent(e);
}
})(console)
";d.body.appendChild(e)})(document));

Related

Programmatically download the QR image

I tried to create a QR code with QRcode.js library. As of the UI, I can manually click on the button download to download it but I would to download automatically without clicking the button.
Base on my code bellow.
function genQR(link_string){
let qr_code_element = document.querySelector(".qr-code");
if (link_string != "") {
if (qr_code_element.childElementCount == 0) {
generate(qr_code_element, link_string);
} else {
qr_code_element.innerHTML = "";
generate(qr_code_element, link_string);
}
} else {
alert("not valid QR input");
qr_code_element.style = "display: none";
}
}
function generate(qr_code_element, link_string) {
qr_code_element.style = "";
var qrcode = new QRCode(qr_code_element, {
text: link_string,
width: 200,
height: 200,
colorDark : "#000000",
colorLight : "#ffffff",
correctLevel: QRCode.CorrectLevel.H
});
let download = document.createElement("button");
// qr_code_element.appendChild(download);
let download_link = document.createElement("a");
download_link.setAttribute("download", "qr.png");
download_link.setAttribute("id", "downloadbtn");
download_link.innerText = "Download";
// download.appendChild(download_link);
let qr_code_img = document.querySelector(".qr-code img");
let qr_code_canvas = document.querySelector("canvas");
if (qr_code_img.getAttribute("src") == null) {
setTimeout(() => {
download_link.setAttribute("href", `${qr_code_canvas.toDataURL()}`);
}, 300);
} else {
setTimeout(() => {
download_link.setAttribute("href", `${qr_code_img.getAttribute("src")}`);
}, 300);
}
var clickEvent = new MouseEvent("click", {
"view": window,
"bubbles": true,
"cancelable": false
});
//I expect the below line will automatically download the QR but nothing fires.
download_link.dispatchEvent(clickEvent);
}
If I use button to click and download by hand will works fine for me but I want to reduce too many steps.
I think I almost done here but failed.
Could anyone show me how to automatic download?
Thank you in advance.
I've had this issue in the past, and I've worked around it by creating a small util function I can invoke upon button pressing. But invoking it directly at the end of your function should have the same result as a user click, effectively automatically downloading the QR code without user input.
export function download(blob, filename) {
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.style.display = 'none';
a.href = url;
a.download = filename
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
}
I'm guessing you could try passing generate as the first parameter if the object you're getting is a Blob. Otherwise, you'll probably need to convert it before.
I done my target by adding the source you shared at the bottom of my code and then added this function to convert dataURL to Blob
function dataURItoBlob(dataURI) {
var byteString = atob(dataURI.split(',')[1]);
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
var blob = new Blob([ab], {type: mimeString});
return blob;
}
Thank you very much #Gianmarco Rengucci
I rate for you

Function expected error while pressing download button

When I am pressing the download button on my website in Microsoft Edge, I am getting the "Function expected" error.
download() {
this.element = document.getElementById("img") as HTMLElement;
let dataurl = this.element.innerHTML;
let myRegexp = /(?:^|\s)src=(.*?)(?:\s|$)/g;
let match = myRegexp.exec(dataurl);
let match1 = match[1].replace('"></div>', '');
this.ImageURL = match1;
let block = this.ImageURL.split(";");
let contentType = block[0].split(":")[1];
let realData = block[1].split(",")[1];
let file = this.dataURLtoFile(this.ImageURL, 'QRCode.png');
}
dataURLtoFile(dataurl, filename) {
var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
var a = document.createElement("a");
document.body.appendChild(a);
var blob = new Blob([new File([u8arr], filename, { type: mime })], { type: 'mime' }),
url = window.URL.createObjectURL(blob);
a.href = url;
a.download = `QRCode.png`;
a.click();
setTimeout(function () {
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
}, 100);
return new File([u8arr], filename, { type: mime });
}
The file should download:
Here is the error:
[object Error]: {description: "Function expected", message: "Function
expected", number: -2146823286, stack: "TypeError: Function expected
at n.prototype.dataURLtoFile
(http://instacei.com/1.bb25259c0233e7528077.js:1:237067) at
n.prototype.download
(http://instacei.com/1.bb25259c0233e7528077.js:1:236764) at Anonymous
function (http://instacei.com/1.bb25259c0233e7528077.js:1:155143) at
handleEvent
(http://instacei.com/main.1533bf301f026a959db3.js:1:117135) at
handleEvent
(http://instacei.com/main.1533bf301f026a959db3.js:1:138938) at Lr
(http://instacei.com/main.1533bf301f026a959db3.js:1:87225) at
Anonymous function
(http://instacei.com/main.1533bf301f026a959db3.js:1:93361) at
Anonymous function
(http://instacei.com/main.1533bf301f026a959db3.js:1:284082) at
e.prototype.invokeTask
(http://instacei.com/polyfills.481858ef51fe27531859.js:1:7664) at
onInvokeTask
(http://instacei.com/main.1533bf301f026a959db3.js:1:55627)"}

createObjectURL() does not generate an appropriate image URL

I am using JavaScript to generate an image URL. When I opened the url generated, the image is just a small rectangle with black background, which is not the image I want at all. Hence, I am not sure where the problem is.
My response from the backend is:
filename=imageName, imageData = base64Image, dataUrl =
"data:image/gif;base64," + base64Image
str.split(':').pop().split(';')[0]; -> this line is equal to image/gif
axios.post('/convert/image', fd, {'Content-Type' : 'multipart/form-data'})
.then (res => {
// decoded = base64.decodebytes(res.data.imageData);
// console.log(decoded);
var encodedString = btoa(res.data.imageData);
// console.log(encodedString);
var decodedData = window.atob(encodedString);
var byteNumbers = new Array(decodedData.length);
for (var i = 0; i < decodedData.length; i++) {
byteNumbers[i] = decodedData.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
var str = res.data.dataUrl;
var type = str.split(':').pop().split(';')[0];
var blob = new Blob([JSON.stringify(byteArray)], {type: type});
console.log(blob);
var e = document.createEvent('MouseEvents'),
a = document.createElement('a');
a.download = 'download';
var urlCreator = window.URL || window.webkitURL;
a.href = urlCreator.createObjectURL(blob);
a.dataset.downloadurl = [type, a.download, a.href].join(':');
console.log(a.dataset.downloadurl);
e.initEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
a.dispatchEvent(e);
urlCreator.revokeObjectURL(a.href);
});

How to print or debug a value in json file

How to use a debugger like console.log() to write in JSON file and debug values.
Why don't you just save the console.log output to a file?
Right click > Save as in the Console.
Otherwise there's the console.save JavaScript that may help you if I'm understanding your question properly.
http://bgrins.github.io/devtools-snippets/#console-save
(function(console){
console.save = function(data, filename){
if(!data) {
console.error('Console.save: No data')
return;
}
if(!filename) filename = 'console.json'
if(typeof data === "object"){
data = JSON.stringify(data, undefined, 4)
}
var blob = new Blob([data], {type: 'text/json'}),
e = document.createEvent('MouseEvents'),
a = document.createElement('a')
a.download = filename
a.href = window.URL.createObjectURL(blob)
a.dataset.downloadurl = ['text/json', a.download, a.href].join(':')
e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
a.dispatchEvent(e)
}
})(console)
Usage:
console.save(data, [filename])

How to make json more legible

I have looked at some issues like:
How can I pretty-print JSON using JavaScript?
and
Javascript: How to generate formatted easy-to-read JSON straight from an object?
and
http://jsfiddle.net/AndyE/HZPVL/
But I cannot get it to work for me. I must be doing something wrong? Can anyone advise?
I tried adding '\t' to the stringify part, but it did not work for me
$(document).on("click", "#doBackupBtn", function(e) {
e.preventDefault();
console.log("Begin backup process");
$.when(
backup("allergies")
).then(function(allergies, log) {
console.log("All done");
//Convert to JSON
var data = {allergies:allergies}
var serializedData = JSON.stringify(data, '\t');
console.log(serializedData);
(function(console){
console.save = function(data, filename){
if(!data) {
console.error('Console.save: No data')
return;
}
if(!filename) filename = 'console.json'
if(typeof data === "object"){
data = JSON.stringify(data)
}
var blob = new Blob([data], {type: 'text/json'}),
e = document.createEvent('MouseEvents'),
a = document.createElement('a')
a.download = filename
a.href = window.URL.createObjectURL(blob)
a.dataset.downloadurl = ['text/json', a.download, a.href].join(':')
e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
a.dispatchEvent(e)
}
})(console)
The \t is on third argument. Try this on your browser console ( FF Ctrl+Shift+K ) :
console.log(JSON.stringify({"a": {"b": "c"}}, null, 4));
Result:
"{
"a": {
"b": "c"
}
}"
You are missing the JSON.stringify(obj, undefined, 2)

Categories

Resources