在网页中使用 zxing Barcode Scanner [英] Using zxing Barcode Scanner within a web page

查看:38
本文介绍了在网页中使用 zxing Barcode Scanner的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有工作示例如何从网页使用 zxing 条码扫描仪?

参考本文档:https://github.com/zxing/zxing/wiki/Scanning-From-Web-Pages

下面的测试代码不应该工作吗?

function Test1(){$.ajax({url: "zxing://scan/?ret=http%3A%2F%2Ffoo.com%2Fproducts%2F%7BCODE%7D%2Fdescription&SCAN_FORMATS=UPC_A,EAN_13",成功:功能(){警报(成功");},错误:函数(){警报(错误");}});}函数 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",成功:功能(){警报(成功");},错误:函数(){警报(错误");}});}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><button id="button1" onClick="Test1();">测试 1</button><br><br><button id="button2" onClick="Test2();">Test 2</button>

我的 Android 4.4.2 Samsung Galaxy TabPro 和 Samsung Galaxy S4 不断出现错误".我试过普通浏览器、Chrome、Firefox 和 Dolphin 浏览器.

即使 http://zxing.appspot.com/scan 也不起作用,因为它总是要求我安装 (已安装)应用.

任何帮助将不胜感激.

解决方案

ZXing 不是为与 AJAX 一起使用而设计的.相反,它通过在默认浏览器中打开一个解析的 URL 来工作.从那时起,浏览器的行为主要负责用户体验.

关于此,有几种方法已发布;不幸的是,没有一种方法适用于所有浏览器.

有些浏览器,当您从命令行打开它们时,会检查 URL 是否已经在另一个选项卡中打开,如果是,将使用该选项卡而不是新的选项卡.如果 zxing 链接包含zxing://scan/?ret=mytab.html#{CODE}",这将导致onhashchange"事件.

其他浏览器不执行这样的检查,所以我们最终得到多个标签,所有标签都具有相同的 URL(哈希除外),并且没有一个引发hashchanged"事件.对于这些浏览器,我们需要尽可能重用缓存中的页面(以防止每次扫描时的网络流量),并将 localStorage 值更改为哈希值.如果浏览器能够监听storage"事件,我们就可以使用它来触发代码.

以下代码适用于 Chrome、Android 固有浏览器和 Firefox.它可能适用于其他人,但我还没有尝试过.但是,Firefox 的一个警告是,只有在 about:config 设置dom.allow_scripts_to_close_windows"设置为true"时,扫描仪窗口才会关闭.

** 经过编辑,可以更好地处理允许扫描的多个页面,现在您可以使用不同的哈希值而不会干扰代码.**

新版本 12/19/16

<HTML><头部><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";//如果不允许self.close}<SCRIPT type="text/javascript" >var changesHash = false;功能 onbarcode(事件){开关(事件.类型){案例哈希变化":{如果(变化哈希 == 真){返回;}var hash = window.location.hash;if(hash.substr(0,3) == "#zx"){hash = window.location.hash.substr(3);更改哈希 = 真;window.location.hash = event.oldURL.split("#")[1] ||"改变哈希 = 假;处理条码(哈希);}休息;}案例存储":{window.focus();if(event.key ==条形码"){window.removeEventListener("storage", onbarcode, false);processBarcode(event.newValue);}休息;}默认:{控制台日志(事件)休息;}}}window.addEventListener("hashchange", onbarcode, false);函数 getScan(){var href = window.location.href;var ptr = href.lastIndexOf("#");如果(ptr>0){href = href.substr(0,ptr);}window.addEventListener("storage", onbarcode, false);setTimeout('window.removeEventListener("storage", onbarcode, false)', 15000);localStorage.removeItem("条码");//window.open (href + "#zx" + new Date().toString());if(navigator.userAgent.match(/Firefox/i)){//用于火狐浏览器.如果 Chrome 使用它,它只会引发hashchanged"事件.window.location.href = ("zxing://scan/?ret=" + encodeURIComponent(href + "#zx{CODE}"));}别的{//用于Chrome.如果 Firefox 使用它,它会打开扫描窗口.window.open ("zxing://scan/?ret=" + encodeURIComponent(href + "#zx{CODE}"));}}函数处理条码(BC){document.getElementById("scans").innerHTML += "

"+ bc + "</div>";//将您的代码放在上面的行中.}</脚本><META name="viewport" content="width=device-width, initial-scale=1"/><身体><输入id=条形码类型=文本><INPUT style="width:100px;height:100px" type=button value="Scan" onclick="getScan();"><div id="扫描"></div></身体></HTML>

您可以为最上面的脚本块制作一个 JS 包含文件,并将其包含在您需要扫描功能的所有页面上.

然后在您的文档正文中,您可以在某处设置一个事件来调用 getZxing(),它将调用您写入页面的 processBarcode(barcode).包括一个简单的例子.

附注:第一次从页面运行 zxing 时,系统会要求您选择一个默认应用.确保您选择了与运行页面相同的浏览器.此外,如果您之前为 zxing 选择了默认浏览器,并且想要更改用于 zxing 的浏览器,则需要清除其他浏览器的默认设置.

非常感谢@sean-owen 的辛勤工作和出色的产品.

更新 12/19/16

好的,我做了一个稍微更强大的版本,可以很好地与 Firefox 和 Chrome 配合使用.我发现了一些事情:

如果扫描器未设置为自动打开 Chrome,Chrome 将使用 Storage 事件,并在其成为默认值后使用 Hash 事件.

Firefox 永远不会使用 Hash 事件,但会打开一个额外的窗口,除非您使用 window.location.href 调用扫描器(谢谢,@Roland)

还有其他一些异常情况,但没有破坏交易.

我在散列中留下了zx"前缀,以便代码可以区分扫描仪散列和常规散列.如果你把它留在那里,你不会在 processBarcode 函数中注意到它,非 zx 哈希将按预期运行.

Is there a working example how you can use the zxing Barcode Scanner from a web page?

Referring to this documentation: 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.

Even http://zxing.appspot.com/scan doesn't work as it always asks me to install the (already installed) app.

Any help would be much appreciated.

解决方案

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.

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}".

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.

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".

** 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

<!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.

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.

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.

Many thanks to @sean-owen for his hard work and fantastic product.

UPDATE 12/19/16

Ok, I did a slightly more robust version that works well with Firefox and Chrome. A couple of things I discovered:

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.

Firefox will never use the Hash event, but opens an extra window unless you call the scanner with window.location.href (Thanks, @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.

这篇关于在网页中使用 zxing Barcode Scanner的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆