I am trying to implement a QR code scanner on my Wordpress page or in a popup, so when users visit the page/popup link, he/she will be able to scan a QR code. The QR code is basically a woocommerce product url, so I want the QR code scanner to only proceed if the QR code is generated from my site. Other QR codes, that are not generated from my site, can be read but just show information like URL or code without redirecting to the URL.
The scenario is: I create a woocommerce product with the QR code, then I place QR code on menu/table in restoran. Users will visit my site and open the QR code scanner page, then scan the QR code, and they will be automatically redirected to the woocommerce product. If the QR code is not generated from my website it will not redirect but just show information inside the QR code.
I found this WP plugin but it's totally not working: https://github.com/eManagerNYC/QR-Code-Scanner
I found another method using an html5 QRcode scanner from this: https://github.com/dwa012/html5-qrcode
But it's about 4 years old, and this JavaScript QR Code scanner for HTML5 supporting browsers: https://github.com/jbialobr/JsQRScanner but I don't know how to install or implement it.
Place all the files from the js directory on your server.
Add the js script into your page.
<script type="text/javascript" src="/js/jsqrscanner.nocache.js"></script>
Create a scanner control and append it to the DOM.
<script type="text/javascript">
function onQRCodeScanned(scannedText)
{
var scannedTextMemo = document.getElementById("scannedTextMemo");
if(scannedTextMemo)
{
scannedTextMemo.value = scannedText;
}
}
//this function will be called when JsQRScanner is ready to use
function JsQRScannerReady()
{
//create a new scanner passing to it a callback function that will be invoked when
//the scanner succesfully scan a QR code
var jbScanner = new JsQRScanner(onQRCodeScanned);
//reduce the size of analyzed images to increase performance on mobile devices
jbScanner.setSnapImageMaxSize(300);
var scannerParentElement = document.getElementById("scanner");
if(scannerParentElement)
{
//append the jbScanner to an existing DOM element
jbScanner.appendTo(scannerParentElement);
}
}
</script>
Providing a video stream in a custom way:
<script type="text/javascript">
function onQRCodeScanned(scannedText)
{
var scannedTextMemo = document.getElementById("scannedTextMemo");
if(scannedTextMemo)
{
scannedTextMemo.value = scannedText;
}
}
//funtion returning a promise with a video stream
function provideVideoQQ()
{
return navigator.mediaDevices.enumerateDevices()
.then(function(devices) {
var exCameras = [];
devices.forEach(function(device) {
if (device.kind === 'videoinput') {
exCameras.push(device.deviceId)
}
});
return Promise.resolve(exCameras);
}).then(function(ids){
if(ids.length === 0)
{
return Promise.reject('Could not find a webcam');
}
return navigator.mediaDevices.getUserMedia({
video: {
'optional': [{
'sourceId': ids.length === 1 ? ids[0] : ids[1]//this way QQ browser opens the rear camera
}]
}
});
});
}
//this function will be called when JsQRScanner is ready to use
function JsQRScannerReady()
{
//create a new scanner passing to it a callback function that will be invoked when
//the scanner succesfully scan a QR code
var jbScanner = new JsQRScanner(onQRCodeScanned, provideVideoQQ);
//reduce the size of analyzed images to increase performance on mobile devices
jbScanner.setSnapImageMaxSize(300);
var scannerParentElement = document.getElementById("scanner");
if(scannerParentElement)
{
//append the jbScanner to an existing DOM element
jbScanner.appendTo(scannerParentElement);
}
}
</script>
If anyone can help me with how to implement this code on wordpress page it will be really appreciated.
The credit of this work goes to Chris Schmich
https://github.com/schmich
The code was designed to alert the content of the QR code scanner I have modified it slightly to display the QR code into the web browser instead of the local alert message.
This methods works it will open the URL Link that is encoded in your QRCode in a new window tab, make sure you download the libraries from
https://github.com/schmich/instascan/releases
It works 100% provided you should download the libraries from the above link and add in the src of script tag inside the head tag.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://rawgit.com/schmich/instascan-builds/master/instascan.min.js"></script>
<style>
#preview{
width:500px;
height: 500px;
margin:0px auto;
}
</style>
</head>
<body>
<h1 style="color:blue">Scan your QRCode</h1>
<video id="preview"></video>
<script src="https://rawgit.com/schmich/instascan-builds/master/instascan.min.js"></script>
<script type="text/javascript">
var scanner = new Instascan.Scanner({ video: document.getElementById('preview'), scanPeriod: 5, mirror: false });
scanner.addListener('scan',function(content){
window.location.href=content;
});
Instascan.Camera.getCameras().then(function (cameras){
if(cameras.length>0){
scanner.start(cameras[0]);
$('[name="options"]').on('change',function(){
if($(this).val()==1){
if(cameras[0]!=""){
scanner.start(cameras[0]);
}else{
alert('No Front camera found!');
}
}
});
}else{
console.error('No cameras found.');
alert('No cameras found.');
}
}).catch(function(e){
console.error(e);
});
</script>
<div class="btn-group btn-group-toggle mb-5" data-toggle="buttons">
<label class="btn btn-primary active">
<input type="radio" name="options" value="1" autocomplete="off" checked> Front Camera
</label>
</div>
</body>
</html>
To generate qrcode you can use the following code snippet,
$qrcode = base_url().'MPDF/mpdf/index'; //your URL Link here goes inhere after '=' assign it to $qrcode
$this->load->library('ciqrcode');
$params['data'] = $qrcode;
$params['level'] = 'H';
$params['size'] = 10;
$params['savename'] = FCPATH.'public/uploads/tes.png';
$this->ciqrcode->generate($params);
Related
first of all I'm relatively new to javascript. So I'm sorry if my question is dumb. I would like to draw a molecule on my webiste by using this tool https://github.com/rdkit/rdkit-js. I also found an example here https://iwatobipen.wordpress.com/2021/12/29/create-desktop-chemoinformatics-application-with-js-chemoinformatics-rdkit-js/comment-page-1/. This example works in my case but when i try to invoke a function to draw a molecule as a .svg without using the example code, I fail. I get this error-message in my browser:
Uncaught ReferenceError: RDKit is not defined
at drawmol (results:21:15)
at results:33:5
In the following code example you can see the first case where it works and the second case were it doesn't. In both cases i use the same function.:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://unpkg.com/#rdkit/rdkit/dist/RDKit_minimal.js"></script>
<title>Document</title>
<script>
window
.initRDKitModule()
.then(function (RDKit) {
console.log("RDKit version: " + RDKit.version());
window.RDKit = RDKit;
})
.catch(() => {
});
</script>
<script> var drawmol = function() {
var mol = RDKit.get_mol("C1=CC=C(C=C1)O"); // the string here is a string representation of chemical molecules, it could also be something like "CO" or "CCCCC", shouldnt be important
var svg = mol.get_svg();
document.getElementById("drawer").innerHTML = svg;
};
</script>
</head>
<body>
<button type='button' onclick='drawmol()'> <!-- this works -->
draw
</button><br>
<script>
// drawmol() //this doesnt work
</script>
<div id='drawer'></div>
</body>
</body>
</html>
Later i would like to use the module to dynamically make those images. I use django as the framework. In this case i tried to present a minimal example without the django stuff.
Thanks in advance for your effort!
You are calling drawmol() before RDKit is ready.
To fix this, place it after RDKit is loaded:
window
.initRDKitModule()
.then(function (RDKit) {
console.log("RDKit version: " + RDKit.version());
window.RDKit = RDKit;
//Now RDKit is loaded you can safely call drawmol()
drawmol();
})
.catch(() => {
});
just to set the scene I'm figuring out web development on my own so don't have a lot of knowledge and I hope you could help me out.
So the concept is on HTML page 1 I choose a image and due to the clicking I change it in the second html page.
This is the js file linked to the first html page. Here I store my source of the chosen image in the variable result.
result="";
document.getElementById("choice1").addEventListener("click", function() {
var elem =document.getElementById("choice1");
result = window.getComputedStyle(elem, null).getPropertyValue("background-image");
return result
});
document.getElementById("choice2").addEventListener("click", function() {
var elem =document.getElementById("choice2");
result = window.getComputedStyle(elem, null).getPropertyValue("background-image");
return result
});
document.getElementById("choice3").addEventListener("click", function() {
var elem =document.getElementById("choice3");
result = window.getComputedStyle(elem, null).getPropertyValue("background-image");
return result
});
The second html is shown below. The source of the image (here set at nature) should be changed when I choose another image on the first html through the previous js file above
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style2.css">
</head>
<body>
<img id="current" src="nature.jpg" width="100%" height=auto>
<script src="main.js"></script>
<script src="expose.js"></script>
</body>
</html>
The js file for the second html looks like this. I use setInterval to make it update automatically only if the current image on html2 isn't the same as the source of the id="current" image
setInterval(currentStatus,3000)
currentStatus{
if(document.getElementById("current").src !== result) {
document.getElementById("current").src = result
console.log("changes applied")
} else {
console.log("nothing changed")
}
}
Thanks for the help !
(ps: I prefer not to work with local storage)
I am trying to implement Wami-Recorder as described here on stackoverflow with basically the same setup as in the accepted answer ie swfobject.js, recorder.js, and gui.js included in the head tag, the html controls contained in the divs:
<div id="recorder">
<button id="record">Record</button>
<button id="play">Play</button>
</div>
<div id="flash"></div>
and the JavaScript is just sitting at the bottom of the page just before the html end tag:
<script>
Wami.setup({
id: 'flash' // where to put the flash object
});
// initialize some global vars
var recording = '';
var recordingUrl = '';
var playBackUrl = '';
// get button elements
var record = $('#record');
var play = $('#play');
// define functions
function startRecording() {
recording = 'temp.wav';
recordingUrl = 'http://localhost/temp/wami/test/save_file.php?filename=' + recording;
Wami.startRecording(recordingUrl);
// update button attributes
record.html('Stop').unbind().click(function() {
stopRecording();
});
}
function stopRecording() {
Wami.stopRecording();
// get the recording for playback
playBackUrl = 'http://localhost/temp/wami/test/' + recording;
// update button attributes
record.html('Record').unbind().click(function() {
startRecording();
});
}
function startPlaying() {
Wami.startPlaying(playBackUrl);
// update button attributes
play.html('Stop').unbind().click(function() {
stopPlaying();
});
}
function stopPlaying() {
Wami.stopPlaying();
// update button attributes
play.html('Play').unbind().click(function() {
startPlaying();
});
}
// add initial click functions
record.click(function() {
startRecording();
});
play.click(function() {
startPlaying();
});
</script>
</body>
Now, I've never actually seen a working demo of Wami-Recorder, but I'm assuming there should actually be something in the flash container when it loads...? I get no error, and I can right click the area where the flash embed should be and the context menu confirms that there's a flash object loaded, and Firebug shows the DOM has been modified to:
<div id="recorder">
<button id="record">Record</button>
<button id="play">Play</button>
</div>
<div id="flash">
<div id="widb06765e52be" style="position: absolute;">
<object id="wid36dd0ea1ccc" width="214" height="137" type="application/x-shockwave-flash" data="Wami.swf" style="visibility: visible;">
<param name="allowScriptAccess" value="always">
<param name="wmode" value="transparent">
<param name="flashvars" value="visible=false&loadedCallback=Wami._callbacks['wid9ebef515c0b']&console=true">
</object>
</div>
</div>
as well as that the Wami.swf file was fetched via GET with 200 status.
Still, when I click the Record button, I get TypeError: Wami.startRecording is not a function. I'm assuming it's some sort of context issue, in that Wami is not a global for use inside a function for some reason. If so, can anyone explain why? If this is not the case, what have I overlooked?
Edit:
At one point I had tried to implement a more object-oriented way of doing things with:
var Audio = {
setup: function() {
Wami.setup("wami");
}
record: function() {
Audio.status("Recording...");
Wami.startRecording("https://wami-recorder.appspot.com/audio");
}
play: function() {
Wami.startPlaying("https://wami-recorder.appspot.com/audio");
}
stop: function() {
Audio.status("");
Wami.stopRecording();
Wami.stopPlaying();
}
status: function(msg) {
$('#status').html(msg);
}
};
And I would fire the functions from within the document.ready() method depending upon other conditions. The original implementation throws the exact same error, and I stripped it all out to try this more direct approach... to no avail.
You're on the right track! This is a lot of writing, but I hope it helps :-D
On the default implementation using the sample code from the Google repos, you do see the Flash GUI because it's initialized, but in this example, it does not and relies on the HTML buttons. The Flash is still on the page right below the buttons but white one white.
Your error
Using your code and files, the only way I was able to duplicate your error was to access the file via the file system:
file:///c:/xampp/htdocs/wami/index.html
Accessing the same content through a web server:
http://localhost/wami/index.html
works great.
So my assumption is that you don't have a web server to test on and are using the file system instead. I included links to XAMPP and basic setup instructions below, as well as the working code sample.
My setup:
I'm using XAMPP so the browser URL is set to http://localhost/wami/index.html.
You can download XAMPP here.
On Windows, it will install in C:\xampp by default.
Place all your files in C:\xampp\htdocs\wami and you should be all set.
Start APACHE in the XAMPP console
Open a browser and navigate to http://localhost/wami/index.html
I placed all files in that folder (all WAMI files including save_file.php). Once ran, and the first WAV file was created, I elevated the permissions on it for testing (right-click, add FULL CONTROL permission for All Users (I'm on Windows 7).
Full working code sample (same as yours but has the entire code chunk for reference. I removed https:// from the JavaScript call since mixing http and https can cause security popups and broken JavaScript)
I used the PHP file as-is with this code:
<?php
// get the filename
parse_str($_SERVER['QUERY_STRING'], $params);
$file = isset($params['filename']) ? $params['filename'] : 'temp.wav';
// save the recorded audio to that file
$content = file_get_contents('php://input');
$fh = fopen($file, 'w') or die("can't open file");
fwrite($fh, $content);
fclose($fh);
?>
And the HTML file:
<!-- index.html -->
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script src="//ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js"></script>
<script src="recorder.js"></script>
</head>
<body>
<div id="recorder">
<button id="record">Record</button>
<button id="play">Play</button>
</div>
<div id="flash"></div>
<script type="text/javascript">
// initialize Wami
Wami.setup({
id: 'flash' // where to put the flash object
});
// initialize some global vars
var recording = '';
var recordingUrl = '';
var playBackUrl = '';
// get button elements
var record = $('#record');
var play = $('#play');
// define functions
function startRecording() {
recording = 'temp.wav';
recordingUrl = 'save_file.php?filename=' + recording;
Wami.startRecording(recordingUrl);
// update button attributes
record.html('Stop').unbind().click(function() {
stopRecording();
});
}
function stopRecording() {
Wami.stopRecording();
// get the recording for playback
playBackUrl = recording;
// update button attributes
record.html('Record').unbind().click(function() {
startRecording();
});
}
function startPlaying() {
Wami.startPlaying(playBackUrl);
// update button attributes
play.html('Stop').unbind().click(function() {
stopPlaying();
});
}
function stopPlaying() {
Wami.stopPlaying();
// update button attributes
play.html('Play').unbind().click(function() {
startPlaying();
});
}
// add initial click functions
record.click(function() {
startRecording();
});
play.click(function() {
startPlaying();
});
</script>
</body>
</html>
The flash object was being embedded in the page, but none of the event listeners were working. I have since switched to jRecorder link, and with a few modifications to the code, have it working with no issues.
I'm struggling trying to get a link to pop up in in the Dropbox chooser drop-in app. I'm using the javascript method and inserting into an html page. The dropbox chooser button shows up, and I'm able to select a file from the dropbox pop-up window, but the result is just a green checkmark and NO link like in the demo (I've tried both the direct and preview method). I've been struggling with this for a few hours. Anyone see anything wrong, or have a good code snipeet they want to share?
Here's my code:
<script type="text/javascript" src="https://www.dropbox.com/static/api/1/dropins.js" id="dropboxjs" data-app-key="XXXXXX"></script>
<!-- Replace data-app-key with yours --> <script type="text/javascript">
// add an event listener to a Chooser button
document.getElementById("db-chooser").addEventListener("DbxChooserSuccess",
function(e) {
alert("Here's the chosen file: " + e.files[0].link)
window.location.href = 'e.files[0].link';
}, false);
</script>
<input data-link-type="direct" id="db-chooser" name="selected-file" type="dropbox-chooser" />
<div id="link-div" style="display: none">Link:</div>
<script type="text/javascript">
document.getElementById("db-chooser").addEventListener("DbxChooserSuccess",
function(e) {
var link = document.getElementById("link");
link.textContent = link.href = e.files[0].link;
document.getElementById("link-div").style.display = "block";
}, false);
</script>
I see two issues in the above code.
The first script references db-chooser before it's actually on the page, so that may not be working at all.
The second script looks for an element called link, but I think you mean link-div.
Finally, you might want to update to the latest version of dropins.js, just because it's the latest. :-) The input tag version has gone away, and instead you can use createChooseButton. Here's a complete working example using the latest version:
<!doctype html>
<html>
<head>
<script src="https://www.dropbox.com/static/api/2/dropins.js" id="dropboxjs" data-app-key="XXXXXX"></script>
</head>
<body>
<div id="container"></div>
<a id="link"></a>
<script>
var button = Dropbox.createChooseButton({
success: function(files) {
var linkTag = document.getElementById('link');
linkTag.href = files[0].link;
linkTag.textContent = files[0].link;
},
linkType: 'direct'
});
document.getElementById('container').appendChild(button);
</script>
</body>
</html>
Okay i have searched al over for a decent example on how to get the HTML 5 IMA SDK from Google working.
I have pasted my code below, all that happens is the HTML 5 video shows up that's it no errors nothing. I don't think the Javascript is even running and I know its because I messed something up. Please help. I just want to display ads into an HTML 5 vid
I have substituted my VAST tag for Googles example tag and used a generic video I found on the web for the src video. Anyone have a suggestion on why this doesnt work.
<video id="videohtml5" width="720" height="405" controls="controls">
<source src="http://www.cncpts.me/complex/html5-IMA/NewBalance_NYCExperience_FINAL.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
var adsManager;
var adsLoader;
var clickTrackingOverlay = document.getElementById('clickTrackingOverlay');
var videoElement = document.getElementById('videohtml5');
var adsLoader = new google.ima.AdsLoader();
// Add event listeners
adsLoader.addEventListener(
google.ima.AdsLoadedEvent.Type.ADS_LOADED,
onAdsLoaded,
false);
adsLoader.addEventListener(
google.ima.AdErrorEvent.Type.AD_ERROR,
onAdError,
false);
// Create request object
var adsRequest = {
adTagUrl: "hhttp://pubads.g.doubleclick.net/gampad/ads?sz=400x300&iu=%2F6062%2Fiab_vast_samples&ciu_szs=300x250%2C728x90&impl=s&gdfp_req=1&env=vp&output=xml_vast2&unviewed_position_start=1&url=[referrer_url]&correlator=[timestamp]&cust_params=iab_vast_samples%3Dlinear",
adType: "video"
};
// Make request
adsLoader.requestAds(adsRequest);
function onAdsLoaded(adsLoadedEvent) {
// Get the ads manager
adsManager = adsLoadedEvent.getAdsManager();
adsManager.addEventListener(google.ima.AdErrorEvent.Type.AD_ERROR, onAdError);
// Listen and respond to events which require you to pause/resume content
adsManager.addEventListener(
google.ima.AdEvent.Type.CONTENT_PAUSE_REQUESTED,
onPauseRequested);
adsManager.addEventListener(
google.ima.AdEvent.Type.CONTENT_RESUME_REQUESTED,
onResumeRequested);
// Set a visual element on which clicks should be tracked for video ads
adsManager.setClickTrackingElement(clickTrackingOverlay);
try {
// Call play to start showing the ad.
adsManager.play(videoElement);
} catch (adError) {
// An error may be thrown if there was a problem with the VAST response.
}
}
function onAdError(adErrorEvent) {
// Handle the error logging.
console.log(adErrorEvent.getError());
}
function onPauseRequested() {
videoElement.pause();
// Setup UI for showing ads (e.g. display ad timer countdown,
// disable seeking, etc.)
// setupUIForAd();
}
function onResumeRequested() {
// Setup UI back for showing content.
// setupUIForContent();
videoElement.play();
}
</script>
figured it out next task is to learn how to run this on an embed object inside an iframe
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="http://www.google.com/uds?file=ima&v=1&nodependencyload=true"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#videohtml5").click(function(){
var adsManager;
var clickTrackingOverlay = document.getElementById('clickTrackingOverlay');
var videoElement = document.getElementById('videohtml5');
var adsLoader = new google.ima.AdsLoader();
// Add event listeners
adsLoader.addEventListener(
google.ima.AdsLoadedEvent.Type.ADS_LOADED,
onAdsLoaded,
false);
adsLoader.addEventListener(
google.ima.AdErrorEvent.Type.AD_ERROR,
onAdError,
false);
// Create request object
var adsRequest = {
adTagUrl: "http://pubads.g.doubleclick.net/gampad/ads?sz=400x300&iu=%2F6062%2Fiab_vast_samples&ciu_szs=300x250%2C728x90&impl=s&gdfp_req=1&env=vp&output=xml_vast2&unviewed_position_start=1&url=[referrer_url]&correlator=[timestamp]&cust_params=iab_vast_samples%3Dlinear",
adType: "video"
};
// Make request
adsLoader.requestAds(adsRequest);
function onAdsLoaded(adsLoadedEvent) {
// Get the ads manager
adsManager = adsLoadedEvent.getAdsManager();
adsManager.addEventListener(google.ima.AdErrorEvent.Type.AD_ERROR, onAdError);
// Listen and respond to events which require you to pause/resume content
adsManager.addEventListener(
google.ima.AdEvent.Type.CONTENT_PAUSE_REQUESTED,
onPauseRequested);
adsManager.addEventListener(
google.ima.AdEvent.Type.CONTENT_RESUME_REQUESTED,
onResumeRequested);
// Set a visual element on which clicks should be tracked for video ads
adsManager.setClickTrackingElement(clickTrackingOverlay);
try {
// Call play to start showing the ad.
adsManager.play(videoElement);
} catch (adError) {
// An error may be thrown if there was a problem with the VAST response.
}
}
function onAdError(adErrorEvent) {
// Handle the error logging.
console.log(adErrorEvent.getError());
}
function onPauseRequested() {
videoElement.pause();
// Setup UI for showing ads (e.g. display ad timer countdown,
// disable seeking, etc.)
// setupUIForAd();
}
function onResumeRequested() {
// Setup UI back for showing content.
// setupUIForContent();
videoElement.play();
}
});
});
</script>
<video id="videohtml5" width="720" height="405" controls="controls" onclick="">
<source src="#" type="video/mp4">
Your browser does not support the video tag.
</video>