-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpopup.js
More file actions
161 lines (152 loc) · 6.09 KB
/
popup.js
File metadata and controls
161 lines (152 loc) · 6.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
(async () => {
const video = document.getElementById('v');
const overlay = document.getElementById('ov');
const octx = overlay.getContext('2d');
const fileInp = document.getElementById('file');
const msg = document.getElementById('msg');
const work = document.createElement('canvas');
const wctx = work.getContext('2d', { willReadFrequently: true });
// ---------- helpers
function show(t){ msg.textContent = t; }
function handle(text){
if (/^https?:\/\//i.test(text)) { chrome.tabs.create({ url: text }); window.close(); }
else show(`Scanned (not a URL): ${text.slice(0,200)}${text.length>200?'…':''}`);
}
function drawBox(points, color='#00c853'){
octx.clearRect(0,0,overlay.width,overlay.height);
if (!points || points.length<2) return;
octx.lineWidth = 3; octx.strokeStyle = color;
octx.beginPath(); octx.moveTo(points[0].x, points[0].y);
for (let i=1;i<points.length;i++) octx.lineTo(points[i].x, points[i].y);
octx.closePath(); octx.stroke();
}
function syncToVideoSize(){
const W = video.videoWidth || 640;
const H = video.videoHeight || 480;
if (!W || !H) return false;
if (overlay.width!==W || overlay.height!==H){
overlay.width=W; overlay.height=H; work.width=W; work.height=H;
}
return true;
}
// simple global threshold (helps dotted/logo QRs)
function thresholdImage(imgData){
const data = imgData.data;
let sum=0;
for (let i=0;i<data.length;i+=4){
const g = (data[i]*0.2126 + data[i+1]*0.7152 + data[i+2]*0.0722);
sum += g;
}
const mean = sum / (data.length/4);
for (let i=0;i<data.length;i+=4){
const g = (data[i]*0.2126 + data[i+1]*0.7152 + data[i+2]*0.0722);
const v = g > mean*0.95 ? 255 : 0; // slightly below mean -> more aggressive
data[i]=data[i+1]=data[i+2]=v; data[i+3]=255;
}
return imgData;
}
// ---------- image file fallback
fileInp.addEventListener('change', async () => {
const f = fileInp.files && fileInp.files[0];
if (!f) return;
const img = new Image();
img.onload = async () => {
work.width = img.naturalWidth; work.height = img.naturalHeight;
wctx.imageSmoothingEnabled = false;
wctx.drawImage(img, 0, 0);
// try ZXing first
if (globalThis.ZXing){
try {
const reader = new ZXing.BrowserQRCodeReader();
const tmp = document.createElement('img'); tmp.src = work.toDataURL('image/png');
const res = await reader.decodeFromImageElement(tmp);
if (res && res.text) return handle(res.text);
} catch {}
}
// then jsQR with preprocessing
let imgData = wctx.getImageData(0,0,work.width,work.height);
const res1 = jsQR(imgData.data, work.width, work.height, { inversionAttempts:"attemptBoth" });
if (res1 && res1.data) return handle(res1.data);
imgData = thresholdImage(imgData); // binarize
wctx.putImageData(imgData,0,0);
const res2 = jsQR(imgData.data, work.width, work.height, { inversionAttempts:"dontInvert" });
if (res2 && res2.data) return handle(res2.data);
show('Couldn’t decode this image. Try a flatter/brighter shot.');
};
img.src = URL.createObjectURL(f);
});
// ---------- camera start (native ZXing → BarcodeDetector → jsQR)
let stream;
try {
stream = await navigator.mediaDevices.getUserMedia({
video: { width:{ideal:1920}, height:{ideal:1080}, frameRate:{ideal:30, max:30} }
});
video.srcObject = stream;
} catch(e){ show(`Camera failed: ${e.name||''} ${e.message||e}`); return; }
// prefer ZXing; let ZXing control video.play()
if (globalThis.ZXing){
try { video.pause(); } catch {}
const reader = new ZXing.BrowserQRCodeReader();
reader.decodeFromVideoElementContinuously(video, (result, err) => {
if (result && result.text){
const pts=(result.resultPoints||[]).map(p=>({x:p.x,y:p.y}));
if (syncToVideoSize() && pts.length>=3) drawBox(pts, '#1abc9c');
handle(result.text);
}
});
window.addEventListener('unload', () => { try{reader.reset();}catch{}; stream?.getTracks().forEach(t=>t.stop()); });
return;
}
// else BarcodeDetector if present
const hasBD = 'BarcodeDetector' in globalThis;
if (hasBD){
try { await video.play(); } catch {}
const detector = new BarcodeDetector({ formats:['qr_code'] });
const loop = () => {
if (!syncToVideoSize()) return requestAnimationFrame(loop);
detector.detect(video).then(codes=>{
if (codes && codes.length){
const pts = codes[0].cornerPoints?.map(p=>({x:p.x,y:p.y}));
if (pts) drawBox(pts);
handle(codes[0].rawValue);
} else {
octx.clearRect(0,0,overlay.width,overlay.height);
}
requestAnimationFrame(loop);
}).catch(()=>requestAnimationFrame(loop));
};
requestAnimationFrame(loop);
window.addEventListener('unload', () => { stream?.getTracks().forEach(t=>t.stop()); });
return;
}
// fallback: jsQR with preprocessing
try { await video.play(); } catch {}
const loopJS = () => {
if (!syncToVideoSize()) return requestAnimationFrame(loopJS);
// draw native resolution, then preprocess
wctx.imageSmoothingEnabled = false;
wctx.filter = "contrast(150%) brightness(115%) grayscale(100%)";
wctx.drawImage(video, 0, 0, work.width, work.height);
wctx.filter = "none";
let imgData = wctx.getImageData(0,0,work.width,work.height);
let res = jsQR(imgData.data, work.width, work.height, { inversionAttempts:"attemptBoth" });
if (!res){
imgData = thresholdImage(imgData);
res = jsQR(imgData.data, work.width, work.height, { inversionAttempts:"dontInvert" });
}
if (res){
drawBox([
res.location.topLeftCorner,
res.location.topRightCorner,
res.location.bottomRightCorner,
res.location.bottomLeftCorner
]);
handle(res.data);
} else {
octx.clearRect(0,0,overlay.width,overlay.height);
}
requestAnimationFrame(loopJS);
};
requestAnimationFrame(loopJS);
window.addEventListener('unload', () => { stream?.getTracks().forEach(t=>t.stop()); });
})();