javascript 在网页中使用 zxing Barcode Scanner
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26356626/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using zxing Barcode Scanner within a web page
提问by CrazyTea
Is there a working example how you can use the zxing Barcode Scanner from a web page?
是否有一个工作示例如何从网页使用 zxing 条码扫描仪?
Referring to this documentation: https://github.com/zxing/zxing/wiki/Scanning-From-Web-Pages
参考本文档:https: //github.com/zxing/zxing/wiki/Scanning-From-Web-Pages
shouldn't the following test code work?
下面的测试代码不应该工作吗?
function Test1()
{
$.ajax(
{
url: "zxing://scan/?ret=http%3A%2F%2Ffoo.com%2Fproducts%2F%7BCODE%7D%2Fdescription&SCAN_FORMATS=UPC_A,EAN_13",
success:function()
{
alert("success");
},
error:function()
{
alert("error");
}
});
}
function Test2()
{
$.ajax(
{
url: "http://zxing.appspot.com/scan?ret=http%3A%2F%2Ffoo.com%2Fproducts%2F%7BCODE%7D%2Fdescription&SCAN_FORMATS=UPC_A,EAN_13",
success:function()
{
alert("success");
},
error:function()
{
alert("error");
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="button1" onClick="Test1();">Test 1</button>
<br>
<br>
<button id="button2" onClick="Test2();">Test 2</button>
I keep getting "error" on my Android 4.4.2 Samsung Galaxy TabPro and Samsung Galaxy S4. I've tried the stock browser, Chrome, Firefox and Dolphin Browser.
我的 Android 4.4.2 Samsung Galaxy TabPro 和 Samsung Galaxy S4 上不断出现“错误”。我尝试过股票浏览器、Chrome、Firefox 和 Dolphin Browser。
Even http://zxing.appspot.com/scandoesn't work as it always asks me to install the (already installed) app.
甚至http://zxing.appspot.com/scan也不起作用,因为它总是要求我安装(已安装)应用程序。
Any help would be much appreciated.
任何帮助将非常感激。
回答by alfadog67
ZXing isn't designed to work with AJAX. Instead, it works by opening a parsed URL in the default browser. The behavior of the browser is mainly what's responsible for the user experience from that point forward.
ZXing 不是为与 AJAX 一起使用而设计的。相反,它通过在默认浏览器中打开一个解析的 URL 来工作。从那时起,浏览器的行为主要负责用户体验。
There are several methods posted regarding this; unfortunately, there is no one method that will work for every browser.
有几种关于此的方法;不幸的是,没有一种方法适用于所有浏览器。
Some browsers, when you open them from the command line, will check to see if the URL is already opened in another tab, and if so, will use that tab instead of a new one. This will cause a "onhashchange" event if the zxing link contains "zxing://scan/?ret=mytab.html#{CODE}".
某些浏览器,当您从命令行打开它们时,会检查 URL 是否已经在另一个选项卡中打开,如果是,将使用该选项卡而不是新选项卡。如果 zxing 链接包含“zxing://scan/?ret=mytab.html#{CODE}”,这将导致“onhashchange”事件。
Other browsers don't perform such a check, so we wind up with multiple tabs, all having the same URL (with the exception of the hash), and none of them raising the "hashchanged" event. For those browsers, we need to re-use the page from cache if possible (to prevent network traffic on every scan), and change the localStorage value to what the hash is. If the browser is capable of listening for the "storage" event, we can use that to trigger the code.
其他浏览器不执行这样的检查,所以我们最终得到多个选项卡,所有选项卡都具有相同的 URL(哈希除外),并且没有一个引发“hashchanged”事件。对于这些浏览器,我们需要尽可能重用缓存中的页面(以防止每次扫描时的网络流量),并将 localStorage 值更改为哈希值。如果浏览器能够侦听“存储”事件,我们就可以使用它来触发代码。
The code below works with Chrome, the intrinsic Android browser, and Firefox. It might work with others, but I haven't tried. One Firefox caveat, though, is that the scanner window will only close if the about:config setting "dom.allow_scripts_to_close_windows" is set to "true".
下面的代码适用于 Chrome、Android 内在浏览器和 Firefox。它可能适用于其他人,但我还没有尝试过。但是,Firefox 的一个警告是,只有在 about:config 设置“dom.allow_scripts_to_close_windows”设置为“true”时,扫描仪窗口才会关闭。
** This was edited to work better with multiple pages that allow scans, and now you can use have different hashes without interfering with the code. **
** 这已被编辑以更好地处理允许扫描的多个页面,现在您可以使用不同的哈希值而不会干扰代码。**
NEW VERSION 12/19/16
新版本 12/19/16
<!DOCTYPE html>
<HTML>
<HEAD>
<script type="text/javascript">
if(window.location.hash.substr(1,2) == "zx"){
var bc = window.location.hash.substr(3);
localStorage["barcode"] = decodeURI(window.location.hash.substr(3))
window.close();
self.close();
window.location.href = "about:blank";//In case self.close isn't allowed
}
</script>
<SCRIPT type="text/javascript" >
var changingHash = false;
function onbarcode(event){
switch(event.type){
case "hashchange":{
if(changingHash == true){
return;
}
var hash = window.location.hash;
if(hash.substr(0,3) == "#zx"){
hash = window.location.hash.substr(3);
changingHash = true;
window.location.hash = event.oldURL.split("\#")[1] || ""
changingHash = false;
processBarcode(hash);
}
break;
}
case "storage":{
window.focus();
if(event.key == "barcode"){
window.removeEventListener("storage", onbarcode, false);
processBarcode(event.newValue);
}
break;
}
default:{
console.log(event)
break;
}
}
}
window.addEventListener("hashchange", onbarcode, false);
function getScan(){
var href = window.location.href;
var ptr = href.lastIndexOf("#");
if(ptr>0){
href = href.substr(0,ptr);
}
window.addEventListener("storage", onbarcode, false);
setTimeout('window.removeEventListener("storage", onbarcode, false)', 15000);
localStorage.removeItem("barcode");
//window.open (href + "#zx" + new Date().toString());
if(navigator.userAgent.match(/Firefox/i)){
//Used for Firefox. If Chrome uses this, it raises the "hashchanged" event only.
window.location.href = ("zxing://scan/?ret=" + encodeURIComponent(href + "#zx{CODE}"));
}else{
//Used for Chrome. If Firefox uses this, it leaves the scan window open.
window.open ("zxing://scan/?ret=" + encodeURIComponent(href + "#zx{CODE}"));
}
}
function processBarcode(bc){
document.getElementById("scans").innerHTML += "<div>" + bc + "</div>";
//put your code in place of the line above.
}
</SCRIPT>
<META name="viewport" content="width=device-width, initial-scale=1" />
</HEAD>
<BODY>
<INPUT id=barcode type=text >
<INPUT style="width:100px;height:100px" type=button value="Scan" onclick="getScan();">
<div id="scans"></div>
</BODY>
</HTML>
You can make a JS include file for the top block of script, and include it on all the pages where you need scanning capabilities.
您可以为脚本的顶部块制作一个 JS 包含文件,并将其包含在您需要扫描功能的所有页面上。
Then in the body of your document, you can set an event somewhere to call getZxing(), which will call processBarcode(barcode) that you write into your page. Included is a simple one for example's sake.
然后在您的文档正文中,您可以在某处设置一个事件来调用 getZxing(),它将调用您写入页面的 processBarcode(barcode)。例如,包括一个简单的。
Side Note: The first time you run zxing from your page, you'll be asked to choose a default app. Make sure you chose the same browser that you're running the page from. Additionally, if you previously selected a default broswer for zxing and want to change which browser you use for zxing, you'll need to clear defaults from your other browsers.
旁注:第一次从页面运行 zxing 时,系统会要求您选择一个默认应用程序。确保您选择了与运行页面相同的浏览器。此外,如果您之前为 zxing 选择了默认浏览器并想更改用于 zxing 的浏览器,则需要清除其他浏览器的默认设置。
Many thanks to @sean-owen for his hard work and fantastic product.
非常感谢@sean-owen 的辛勤工作和出色的产品。
UPDATE 12/19/16
更新 12/19/16
Ok, I did a slightly more robust version that works well with Firefox and Chrome. A couple of things I discovered:
好的,我做了一个稍微更健壮的版本,它适用于 Firefox 和 Chrome。我发现了几件事:
Chrome will use the Storage
event if the scanner is not set to open Chrome automatically, and will use the Hash
event after it becomes default.
Chrome将使用的Storage
情况下,如果扫描仪没有被设置为打开Chrome自动,并且将使用Hash
它变得违约后的事件。
Firefox will never use the Hash
event, but opens an extra window unless you call the scanner with window.location.href
(Thanks, @Roland)
Firefox 永远不会使用该Hash
事件,但会打开一个额外的窗口,除非您使用window.location.href
(谢谢,@Roland)调用扫描仪
There are a couple of other anomalies, but no deal breakers.
还有其他一些异常情况,但没有交易破坏者。
I left the "zx" prefix in the hash, so that the code could delineate between scanner hashes and regular hashes. If you leave it in there, you'll not notice it in the processBarcode
function, and non-zx hashes will operate as expected.
我在散列中留下了“zx”前缀,以便代码可以在扫描仪散列和常规散列之间进行划分。如果你把它留在那里,你不会在processBarcode
函数中注意到它,非 zx 哈希将按预期运行。