根据应用程序,与其在 ?val= 处触发返回,不如将其发送到 #val= 并使用 javascripts document.location.hash 解析它?如果您收听 onhashchange 事件(假设它是较新的浏览器或移动设备),您将准备好然后在不刷新页面的情况下进行操作。
请求的示例(假设使用 jQuery):
$(window).one('hashchange', function() {
if(document.location.hash.match('=')){
//we have a code...
var code = document.location.hash.substr(document.location.hash.indexOf('=')+1));
document.location.hash="";
//now do something with scanned code
alert(code);
}
});
var selector = 'body';
var filler = "<p align='center'>This device is not set up to support scanning at the moment.<br><br>"
+"On Android devices, install the <a href='https://play.google.com/store/apps/details?id=com.google.zxing.client.android&feature=search_result'>Barcode Scanner by ZXing</a> app from the Google Play store.<br><br>"
+"You can also manually enter your barcode here: <input type='text' id='code'><input type='button' id='submitcode' value='Check Barcode'>";
+"</p>";
//Set up our html into the element specified in the selector var
$(selector).html("<iframe id='scanner'></iframe>"+filler);
//try to load the zxing app if it exists - if not, error will catch the failed load and default us back to the manual entry form
$('#scanner').error(function(){
$(selector).html(filler);
//if manual form is submitted, append the hash so we can use the one set of logic to manage the codes
$(selector+' #submitcode').click(function(){ document.location.href = document.location.href+"#sku="+$('#code').val(); });
//catch someone hitting return to submit the form as well
$('#code').keydown(function (e){
if(e.keyCode == 13){
$(selector+' #submitcode').click();
}
});
}).attr('src',"zxing://scan/?ret="+escape(window.location.href+"#sku={CODE}"));
//handle manual form submission via button click or return key
$(selector+' #submitcode').click(function(){
document.location.href = document.location.href+"#sku="+$('#code').val();
});
$('#code').keydown(function (e){
if(e.keyCode == 13){
$(selector+' #submitcode').click();
}
});