OneSignal subscribe user through web page using web-push-sdk - javascript

Is there a way in one signal web-push-sdk to add user manually and unsubscribe?
I tried this in my subscribeOneSignal() function but nothing happening.
OneSignal.push(function() {
OneSignal.registerForPushNotifications();
});
I have simple html page where I have two buttons one "Subscribe" and other is "Unsubscribe", now when user click on Subscribe button he should add at one signal and when he clicked on "Unsubscribe" button he shouldn't receive the notifications.
<!DOCTYPE html>
<html>
<head>
<link rel="manifest" href="/manifest.json">
<script src="https://cdn.onesignal.com/sdks/OneSignalSDK.js" async></script>
<script>
var OneSignal = window.OneSignal || [];
OneSignal.push(["init", {
appId: "345345-asdf-345",
autoRegister: false,
notifyButton: {
enable: true
}
}]);
function subscribeOneSignal(){
OneSignal.push(function() {
OneSignal.registerForPushNotifications();
});
OneSignal.push(function() {
OneSignal.registerForPushNotifications({
modalPrompt: true
});
});
}
function unSubscribeOneSignal(){
//unsubscribe functionality goes here
}
</script>
</head>
<body>
<p>OneSingle Testing</p>
<br>
<button onclick="subscribeOneSignal()">Subscribe </button>
<button onclick="unSubscribeOneSignal()">Unsubscribe </button>
</body>
</html>

Here is solution, It may help someone else.
<script src="https://cdn.onesignal.com/sdks/OneSignalSDK.js" async></script>
<script>
var useragentid = null;
var OneSignal = window.OneSignal || [];
OneSignal.push(["init", {
appId: "345345-asdf-345",
autoRegister: false,
notifyButton: {
enable: false
},
persistNotification: false
}]);
//Firstly this will check user id
OneSignal.push(function() {
OneSignal.getUserId().then(function(userId) {
if(userId == null){
document.getElementById('unsubscribe').style.display = 'none';
}
else{
useragentid = userId;
document.getElementById('unsubscribe').style.display = '';
OneSignal.push(["getNotificationPermission", function(permission){
}]);
OneSignal.isPushNotificationsEnabled(function(isEnabled) {
if (isEnabled){
document.getElementById('unsubscribe').style.display = '';
document.getElementById('subscribe').style.display = 'none';
}
else{
document.getElementById('unsubscribe').style.display = 'none';
document.getElementById('subscribe').style.display = '';
}
});
}
});
});
//Secondly this will check when subscription changed
OneSignal.push(function() {
OneSignal.on('subscriptionChange', function (isSubscribed) {
if(isSubscribed==true){
OneSignal.getUserId().then(function(userId) {
useragentid = userId;
}).then(function(){
// this is custom function
// here you can send post request to php file as well.
OneSignalUserSubscription(useragentid);
});
document.getElementById('unsubscribe').style.display = '';
document.getElementById('subscribe').style.display = 'none';
}
else if(isSubscribed==false){
OneSignal.getUserId().then(function(userId) {
useragentid = userId;
});
document.getElementById('unsubscribe').style.display = 'none';
document.getElementById('subscribe').style.display = '';
}
else{
console.log('Unable to process the request');
}
});
});
function subscribeOneSignal(){
if(useragentid !=null){
OneSignal.setSubscription(true);
}
else{
OneSignal.registerForPushNotifications({
modalPrompt: true
});
}
}
function unSubscribeOneSignal(){
OneSignal.setSubscription(false);
}
</script>
<div id="home-top" class="clearfix">
<p>OneSingle Testing</p>
<br>
<button id="subscribe" class="button" onclick="subscribeOneSignal()">Subscribe </button>
<button id="unsubscribe" class="button" onclick="unSubscribeOneSignal()">Unsubscribe </button>
</div>
<style>
.button {
background-color: #008CBA;border: none;color: white;padding: 15px 32px;text-align: center;text-decoration: none;display: inline-block;font-size: 16px;cursor: pointer;
}
</style>

Nice, but I have used it, but it want users to be registered after they login to my site with their emailadress as tag:
<?php
if ($_SESSION['sesId']!='')
{
$sr = mysqli_query($DBD->conn(),"SELECT * from members where id = '".$_SESSION['sesId']."'");
if ($rr = mysqli_fetch_array($sr))
{
if ($rr['pushtag']==1 && $rr['alreadysendpush'] ==0 )
{
?>
var OneSignal = window.OneSignal || [];
OneSignal.push(["init", {
appId: "1c398831-ce91-4a8e-90d8-56cc40b8fa97",
autoRegister:false,
showCredit:false,
disable:false, // betekend geen stanaard bericht als je geaceepteerd hebt notificaties te willen ontvangen
notifyButton: {
enable: true /* Set to false to hide */
},
safari_web_id: 'web.onesignal.auto.379e9ba9-232a-4433-a939-20e3e6310530'
}]
);
OneSignal.push(function() {
/* These examples are all valid */
var isPushSupported = OneSignal.isPushNotificationsSupported();
if (isPushSupported)
{
// Push notifications are supported
OneSignal.isPushNotificationsEnabled().then(function(isEnabled)
{
if (isEnabled)
{
console.log("Push notifications are enabled!");
OneSignal.sendTag("email", "<?=$rr['email']?>", function(tagsSent)
{
// Callback called when tags have finished sending
$.ajax({
type: "POST",
url: "<?=HTML_ROOT?>inc/webpush.php",
data: {
"email": "<?=$rr['email']?>",
"register": "1",
"verification":"<?=$rr['verificatie']?>"
},
dataType: "html"
}).done(function(e) {
});
})
}
else {
console.log("Push notifications are not enabled yet.");
}
});
} else {
// Push notifications are not supported
}
});
<?php
} else {
}
}
}
?>
THis works sometimes with tags and sometimes without tags.
How to make it work that i will only register with email

Related

Integrating Braintree Client token into braintree.client.create

I have limited experience working with JavaScript and am attempting to pass a client token generated on my server into the braintree client create of Braintree's javascript code. I do not know how to pass the ClientToken out of the jQuery post and into the authorization section of braintree.client.create. A portion of my code is below:
<script src="https://js.braintreegateway.com/web/3.34.0/js/client.min.js"></script>
<script src="https://js.braintreegateway.com/web/3.34.0/js/hosted-fields.min.js"></script>
<script src="https://www.paypalobjects.com/api/checkout.js" data-version-4></script>
<script src="https://js.braintreegateway.com/web/3.34.0/js/paypal-checkout.min.js"></script>
<script>
var form = document.querySelector('#register-form');
var submit = document.querySelector('input[type="submit"]');
var ClientToken;
var authPosting = jQuery.post('/path/to/php_scripts/getClientToken.php');
authPosting.done(function( data ) {
ClientToken = data;
console.log(ClientToken);
});
braintree.client.create({
authorization: 'ClientToken'
}, function (clientErr, clientInstance) {
if (clientErr) {
console.error(clientErr);
return;
}
braintree.hostedFields.create({
client: clientInstance,
styles: {
'input': {
'font-size': '15px',
'font-family': 'roboto, verdana, sans-serif',
'font-weight': 'lighter',
'color': 'black'
},
':focus': {
'color': 'black'
},
'.valid': {
'color': 'black'
},
'.invalid': {
'color': 'black'
}
},
fields: {
number: {
selector: '#card-number',
placeholder: ''
},
cvv: {
selector: '#cvv',
placeholder: ''
},
expirationDate: {
selector: '#expiration-date',
placeholder: 'MM/YY'
},
postalCode: {
selector: '#postal-code',
placeholder: ''
}
}
}, function(err, hostedFieldsInstance) {
if (err) {
console.error(err);
return;
}
function findLabel(field) {
return jQuery('.hosted-field--label[for="' + field.container.id + '"]');
}
hostedFieldsInstance.on('focus', function (event) {
var field = event.fields[event.emittedBy];
findLabel(field).addClass('label-float').removeClass('filled');
jQuery(".error-msg").hide();
});
// Emulates floating label pattern
hostedFieldsInstance.on('blur', function (event) {
var field = event.fields[event.emittedBy];
var label = findLabel(field);
if (field.isEmpty) {
label.removeClass('label-float');
} else if (field.isValid) {
label.addClass('filled');
} else {
label.addClass('invalid');
}
});
hostedFieldsInstance.on('empty', function (event) {
var field = event.fields[event.emittedBy];
findLabel(field).removeClass('filled').removeClass('invalid');
});
hostedFieldsInstance.on('validityChange', function (event) {
var field = event.fields[event.emittedBy];
var label = findLabel(field);
if (field.isPotentiallyValid) {
label.removeClass('invalid');
} else {
label.addClass('invalid');
}
});
//Submit function
jQuery("#register-form").validate({
submitHandler: function(form) {
event.preventDefault();
hostedFieldsInstance.tokenize(function (err, payload) {
if (err) {
if (err.code === 'HOSTED_FIELDS_FIELDS_EMPTY') {
var msg = "All credit card fields are required.";
jQuery(".error-msg").text(msg);
jQuery(".error-msg").show();
} else if (err.code === 'HOSTED_FIELDS_FIELDS_INVALID') {
var invalidFields = err.details.invalidFieldKeys;
invalidFields.forEach(function (field) {
if (field == "number") {
var myid = "card-number";
var myobj = "credit card number";
} else if (field == "expirationDate") {
var myid = "expiration-date";
var myobj = "expiration date";
}
jQuery("#" + myid).append("<div class='error-msg'>Please enter a valid " + myobj + ".</div>");
});
} else {
var msg = "There was an error on the form."
alert (msg);
}
return;
}
vfirst = jQuery( "input#firstname" ).val(),
vlast = jQuery( "input#lastname" ).val(),
vemail = jQuery( "input#email" ).val(),
vproof = jQuery( "input[name='proof']" ).val(),
vprice = jQuery( "tr#total td.price" ).data('price'),
vcourse = 1950,
vnonce = 'fake-valid-nonce',
url = '/path/to/php_scripts/placeOrder.php';
// This is where you would submit payload.nonce to your server
// alert('Submit your cc nonce to your server here!');
});
//form.submit();
}
});
});
....more code below....
</script>
Any suggestions would be greatly appreciated.
Answering my own question:
CLIENT_AUTHORIZATION = jQuery.parseJSON(jQuery.ajax({
url: "/path/to/php_scripts/TokenScript.php",
dataType: "json",
async: false
}).responseText);
braintree.client.create({
authorization: CLIENT_AUTHORIZATION.token
}, function (clientErr, clientInstance) {
if (clientErr) {
console.error(clientErr);
return;
} code continues.....
The CLIENT_AUTHORIZATION.token is whatever the token was named on the client authorization script.

How to scan a barcode with livestream through webbrowser on on mobile phone in javascript?

I'm trying to make a way to scan irl barcodes that I have printed out on paper to scan into my php website. It's only when I use the website on my phone, than I can open my phone camera and scan a barcod while he scans the barcode and sends it to my code. The code can than check my database etc.
I found a beautiful plugin to do this called QuaggaJS, I have been playing around with it and at the moment I come further than taking a picture and let it read the barcode and the sends it to my code but I want to let it scan while I hold my camera in front of the barcode so it will close the camera out of himself. Here is an example(on a desktop it would ask permission to open webcam).
In the end I want a button where I click on in my website that opens my camera so I can scan the code and when he finds a barcode he close the camera and show me the information from the product that has this barcode. Is there someone that can help me with it?
Here is some code that I used and played with. (Only works with taking picture)
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script type="text/javascript" src="includes/js/quagga.min.js"></script>
<link href="https://use.fontawesome.com/releases/v5.0.8/css/all.css" rel="stylesheet">
<script type="text/javascript" src="includes/js/quagga.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<style>
#interactive.viewport {position: relative; width: 100%; height: auto; overflow: hidden; text-align: center;}
#interactive.viewport > canvas, #interactive.viewport > video {max-width: 100%;width: 100%;}
canvas.drawing, canvas.drawingBuffer {position: absolute; left: 0; top: 0;}
</style>
<script type="text/javascript">
$(function() {
// Create the QuaggaJS config object for the live stream
var liveStreamConfig = {
inputStream: {
type : "LiveStream",
constraints: {
width: {min: 640},
height: {min: 480},
aspectRatio: {min: 1, max: 100},
facingMode: "environment" // or "user" for the front camera
}
},
locator: {
patchSize: "medium",
halfSample: true
},
numOfWorkers: (navigator.hardwareConcurrency ? navigator.hardwareConcurrency : 4),
decoder: {
"readers":[
{"format":"code_128_reader","config":{}}
]
},
locate: true
};
// The fallback to the file API requires a different inputStream option.
// The rest is the same
var fileConfig = $.extend(
{},
liveStreamConfig,
{
inputStream: {
size: 800
}
}
);
// Start the live stream scanner when the modal opens
$('#livestream_scanner').on('shown.bs.modal', function (e) {
Quagga.init(
liveStreamConfig,
function(err) {
if (err) {
$('#livestream_scanner .modal-body .error').html('<div class="alert alert-danger"><strong><i class="fa fa-exclamation-triangle"></i> '+err.name+'</strong>: '+err.message+'</div>');
Quagga.stop();
return;
}
Quagga.start();
}
);
});
// Make sure, QuaggaJS draws frames an lines around possible
// barcodes on the live stream
Quagga.onProcessed(function(result) {
var drawingCtx = Quagga.canvas.ctx.overlay,
drawingCanvas = Quagga.canvas.dom.overlay;
if (result) {
if (result.boxes) {
drawingCtx.clearRect(0, 0, parseInt(drawingCanvas.getAttribute("width")), parseInt(drawingCanvas.getAttribute("height")));
result.boxes.filter(function (box) {
return box !== result.box;
}).forEach(function (box) {
Quagga.ImageDebug.drawPath(box, {x: 0, y: 1}, drawingCtx, {color: "green", lineWidth: 2});
});
}
if (result.box) {
Quagga.ImageDebug.drawPath(result.box, {x: 0, y: 1}, drawingCtx, {color: "#00F", lineWidth: 2});
}
if (result.codeResult && result.codeResult.code) {
Quagga.ImageDebug.drawPath(result.line, {x: 'x', y: 'y'}, drawingCtx, {color: 'red', lineWidth: 3});
}
}
});
// Once a barcode had been read successfully, stop quagga and
// close the modal after a second to let the user notice where
// the barcode had actually been found.
Quagga.onDetected(function(result) {
if (result.codeResult.code){
$('#scanner_input').val(result.codeResult.code);
Quagga.stop();
setTimeout(function(){ $('#livestream_scanner').modal('hide'); }, 1000);
}
});
// Stop quagga in any case, when the modal is closed
$('#livestream_scanner').on('hide.bs.modal', function(){
if (Quagga){
Quagga.stop();
}
});
// Call Quagga.decodeSingle() for every file selected in the
// file input
$("#livestream_scanner input:file").on("change", function(e) {
if (e.target.files && e.target.files.length) {
Quagga.decodeSingle($.extend({}, fileConfig, {src: URL.createObjectURL(e.target.files[0])}), function(result) {alert(result.codeResult.code);});
}
});
});
</script>
</head>
<body>
<input id="scanner_input" class="form-control" style="width:20%;" placeholder="Barcode" type="text" />
<button class="btn btn-default" type="button" data-toggle="modal" data-target="#livestream_scanner"><i class="fas fa-barcode"></i> Scan</button>
<div class="modal" id="livestream_scanner">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title">Barcode Scanner</h4>
</div>
<div class="modal-footer">
<label class="btn btn-default pull-left">
<i class="fa fa-camera"></i> Use camera app
<input type="file" accept="image/*;capture=camera" capture="camera" class="hidden" />
</label>
<button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
</body>
</html>
Best regards
Took me some time to get it done on myself but I found it out. I also had to get a certificate so my website is secure and allows me to use GetUserMedia(); This is my code that I used now. With $code = $_GET['barcode']; I can take the variable to do other stuff with it, all up to yourself.
php code
<button id="opener">Barcode scanner</button>
<div id="modal" title="Barcode scanner">
<span class="found"></span>
<div id="interactive" class="viewport"></div>
</div>
Javascript/QuaggaJS
$(function() {
var App = {
init : function() {
Quagga.init(this.state, function(err) {
if (err) {
console.log(err);
return;
}
App.attachListeners();
App.checkCapabilities();
Quagga.start();
});
},
checkCapabilities: function() {
var track = Quagga.CameraAccess.getActiveTrack();
var capabilities = {};
if (typeof track.getCapabilities === 'function') {
capabilities = track.getCapabilities();
}
this.applySettingsVisibility('zoom', capabilities.zoom);
this.applySettingsVisibility('torch', capabilities.torch);
},
updateOptionsForMediaRange: function(node, range) {
console.log('updateOptionsForMediaRange', node, range);
var NUM_STEPS = 6;
var stepSize = (range.max - range.min) / NUM_STEPS;
var option;
var value;
while (node.firstChild) {
node.removeChild(node.firstChild);
}
for (var i = 0; i <= NUM_STEPS; i++) {
value = range.min + (stepSize * i);
option = document.createElement('option');
option.value = value;
option.innerHTML = value;
node.appendChild(option);
}
},
applySettingsVisibility: function(setting, capability) {
if (typeof capability === 'boolean') {
var node = document.querySelector('input[name="settings_' + setting + '"]');
if (node) {
node.parentNode.style.display = capability ? 'block' : 'none';
}
return;
}
if (window.MediaSettingsRange && capability instanceof window.MediaSettingsRange) {
var node = document.querySelector('select[name="settings_' + setting + '"]');
if (node) {
this.updateOptionsForMediaRange(node, capability);
node.parentNode.style.display = 'block';
}
return;
}
},
initCameraSelection: function(){
var streamLabel = Quagga.CameraAccess.getActiveStreamLabel();
return Quagga.CameraAccess.enumerateVideoDevices()
.then(function(devices) {
function pruneText(text) {
return text.length > 30 ? text.substr(0, 30) : text;
}
var $deviceSelection = document.getElementById("deviceSelection");
while ($deviceSelection.firstChild) {
$deviceSelection.removeChild($deviceSelection.firstChild);
}
devices.forEach(function(device) {
var $option = document.createElement("option");
$option.value = device.deviceId || device.id;
$option.appendChild(document.createTextNode(pruneText(device.label || device.deviceId || device.id)));
$option.selected = streamLabel === device.label;
$deviceSelection.appendChild($option);
});
});
},
attachListeners: function() {
var self = this;
self.initCameraSelection();
$(".controls").on("click", "button.stop", function(e) {
e.preventDefault();
Quagga.stop();
});
$(".controls .reader-config-group").on("change", "input, select", function(e) {
e.preventDefault();
var $target = $(e.target),
value = $target.attr("type") === "checkbox" ? $target.prop("checked") : $target.val(),
name = $target.attr("name"),
state = self._convertNameToState(name);
console.log("Value of "+ state + " changed to " + value);
self.setState(state, value);
});
},
_accessByPath: function(obj, path, val) {
var parts = path.split('.'),
depth = parts.length,
setter = (typeof val !== "undefined") ? true : false;
return parts.reduce(function(o, key, i) {
if (setter && (i + 1) === depth) {
if (typeof o[key] === "object" && typeof val === "object") {
Object.assign(o[key], val);
} else {
o[key] = val;
}
}
return key in o ? o[key] : {};
}, obj);
},
_convertNameToState: function(name) {
return name.replace("_", ".").split("-").reduce(function(result, value) {
return result + value.charAt(0).toUpperCase() + value.substring(1);
});
},
detachListeners: function() {
$(".controls").off("click", "button.stop");
$(".controls .reader-config-group").off("change", "input, select");
},
applySetting: function(setting, value) {
var track = Quagga.CameraAccess.getActiveTrack();
if (track && typeof track.getCapabilities === 'function') {
switch (setting) {
case 'zoom':
return track.applyConstraints({advanced: [{zoom: parseFloat(value)}]});
case 'torch':
return track.applyConstraints({advanced: [{torch: !!value}]});
}
}
},
setState: function(path, value) {
var self = this;
if (typeof self._accessByPath(self.inputMapper, path) === "function") {
value = self._accessByPath(self.inputMapper, path)(value);
}
if (path.startsWith('settings.')) {
var setting = path.substring(9);
return self.applySetting(setting, value);
}
self._accessByPath(self.state, path, value);
console.log(JSON.stringify(self.state));
App.detachListeners();
Quagga.stop();
App.init();
},
inputMapper: {
inputStream: {
constraints: function(value){
if (/^(\d+)x(\d+)$/.test(value)) {
var values = value.split('x');
return {
width: {min: parseInt(values[0])},
height: {min: parseInt(values[1])}
};
}
return {
deviceId: value
};
}
},
numOfWorkers: function(value) {
return parseInt(value);
},
decoder: {
readers: function(value) {
if (value === 'ean_extended') {
return [{
format: "ean_reader",
config: {
supplements: [
'ean_5_reader', 'ean_2_reader'
]
}
}];
}
return [{
format: value + "_reader",
config: {}
}];
}
}
},
state: {
inputStream: {
type : "LiveStream",
constraints: {
width: {min: 640},
height: {min: 480},
aspectRatio: {min: 1, max: 100},
facingMode: "environment" // or user
}
},
locator: {
patchSize: "medium",
halfSample: true
},
numOfWorkers: 2,
frequency: 10,
decoder: {
readers : [{
format: "code_128_reader",
config: {}
}]
},
locate: true
},
lastResult : null
};
App.init();
Quagga.onDetected(function(result) {
var code = result.codeResult.code;
Quagga.stop();
window.location.href="scannerview.php?barcode=" + code;
});
});

webRTC Ice Candidate not getting processed (How to get webRTC to work)

I am trying to make a simple webRTC app with video and audio. I am using a simple PHP signaling server. Now whenever I try to call the remote client I am getting the errors as shown in pics.
Can anyone please explain what am I doing wring here. The code looks fine as was as I can say but for your reference I have added it here.
<!DOCTYPE html>
<!--
Demo Websocket: Client Code
-------------------------
#Author: ANHVNSE02067
#Website: www.nhatanh.net
#Email: anhvnse#gmail.com
-->
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Echo server - Websocket Demo</title>
<style type="text/css">
*{margin: 0; padding: 0;}
body{
color: black;
font-family: monospace;
font-size: 16px;
}
#screen, #input{
padding: 10px;
border: 1px solid #666;
width: 650px;
margin: 0 auto;
}
#screen{
margin-top: 10px;
height: 1000px;
scroll: auto;
}
#screen p{
margin: 2px;
}
input, button{
font-size: 20px;
padding: 3px;
}
.client{
color: green;
font-weight: bold;
}
.server{
color: red;
font-weight: bold;
}
</style>
<script src="jquery-3.1.1.js"></script>
<script>
$( document ).ready(function() {
// Client here
var socket = null;
var uri = "ws://192.168.0.2:81";
function connect(){
socket = new WebSocket(uri);
if(!socket || socket == undefined) return false;
socket.onopen = function(){
writeToScreen('Connected to server '+uri);
}
socket.onerror = function(){
writeToScreen('Error!!!');
}
socket.onclose = function(){
$('#send').prop('disabled', true);
$('#close').prop('disabled', true);
$('#connect').prop('disabled', false);
writeToScreen('Socket closed!');
}
socket.onmessage = function(e){
console.log("Message from signaling server");
writeToScreen('<span class="server">Server: </span>'+e.data);
var data = JSON.parse(e.data);
switch(data.type) {
case "login":
onLogin(data.success);
break;
case "offer":
onOffer(data.offer, data.name);
break;
case "answer":
onAnswer(data.answer);
break;
case "candidate":
onCandidate(data.candidate);
break;
default:
break;
}
}
// Enable send and close button
$('#send').prop('disabled', false);
$('#close').prop('disabled', false);
$('#connect').prop('disabled', true);
}
function close(){
socket.close();
}
function writeToScreen(msg){
var screen = $('#screen');
screen.append('<p>'+msg+'</p>');
screen.animate({scrollTop: screen.height()}, 10);
}
function clearScreen(){
$('#screen').html('');
}
function sendMessage(){
if(!socket || socket == undefined) return false;
var mess = $.trim($('#message').val());
if(mess == '') return;
writeToScreen('<span class="client">Client: </span>'+mess);
socket.send(mess);
// Clear input
$('#message').val('');
}
$(document).ready(function(){
$('#message').focus();
$('#frmInput').submit(function(){
sendMessage();
});
$('#connect').click(function(){
connect();
});
$('#close').click(function(){
close();
});
$('#clear').click(function(){
clearScreen();
});
});
if (!window.RTCPeerConnection) {
window.RTCPeerConnection = window.webkitRTCPeerConnection;
}
var configuration = {
"iceServers": [
{
"urls": "stun:mmt-stun.verkstad.net"
},
{
"urls": "turn:mmt-turn.verkstad.net",
"username": "webrtc",
"credential": "secret"
}
]
};
myConnection = new RTCPeerConnection(configuration);
console.log("RTCPeerConnection object was created");
console.log(myConnection);
myConnection.onicecandidate = function (event) {
console.log("ice candidate from this browser");
console.log(event.candidate);
if (event.candidate) {
send({
type: "candidate",
candidate: event.candidate
});
}
};
var mediaConstraints = {
'offerToReceiveAudio': 1,
'offerToReceiveVideo': 1
};
var connectToOtherUsernameBtn = document.getElementById("connectToOtherUsernameBtn");
console.log(connectToOtherUsernameBtn);
connectToOtherUsernameBtn.addEventListener("click", function () {
console.log("ice state : "+myConnection.iceGatheringState);
var otherUsername = connectToOtherUsernameBtn.value;
connectedUser = otherUsername;
if (otherUsername.length > 0) {
//make an offer
console.log("Function");
console.log(myConnection);
console.log("offer");
myConnection.createOffer(function (offer) {
send({
type: "offer",
offer: offer
});
myConnection.setLocalDescription(offer);
}, function (error) {
alert("An error has occurred.");
console.log(error);
},mediaConstraints);
}
});
function send(message) {
if (connectedUser) {
message.name = connectedUser;
}
socket.send(JSON.stringify(message));
};
function onOffer(offer, name) {
console.log("ice state : "+myConnection.iceGatheringState);
console.log("offer recieved");
if(myConnection.iceGatheringState=="complete"){
connectedUser = name;
myConnection.setRemoteDescription(new RTCSessionDescription(offer));
myConnection.createAnswer(function (answer) {
myConnection.setLocalDescription(answer);
send({
type: "answer",
answer: answer
});
}, function (error) {
alert("oops...error");
console.log(error);
});
console.log("Answer sent");
}
}
//when another user answers to our offer
function onAnswer(answer) {
console.log("ice state : "+myConnection.iceGatheringState);
console.log("answer recieved");
myConnection.setRemoteDescription(new RTCSessionDescription(answer));
}
//when we got ice candidate from another user
function onCandidate(candidate) {
console.log("we got ice candidate from another user");
console.log(candidate);
myConnection.addIceCandidate(new RTCIceCandidate(candidate));
}
myConnection.onsignalingstatechange=function (event){
console.log(myConnection.signalingState);
console.log("Connection Status: "+myConnection.iceConnectionState);
console.log("ice state : "+myConnection.iceGatheringState);
};
});
</script>
</head>
<body>
<form id="frmInput" action="" onsubmit="return false;">
<div id="screen">
<p>Demo echo server</p>
<p>----------------</p>
</div>
<div id="input">
<input type="text" id="message" placeholder="Message here..">
<button type="submit" id="send" disabled>Send</button>
<button type="button" id="connect">Connect</button>
<button type="button" id="close" disabled>Close</button>
<button type="button" id="clear">Clear</button>
<button id="connectToOtherUsernameBtn" value="arjun">Arjun</button>
<input type="text" id="msgInput" />
<button id="sendMsgBtn">send</button>
</div>
</form>
</body>
</html>
UPDATE: I removed following code
var mediaConstraints = {
'offerToReceiveAudio': 1,
'offerToReceiveVideo': 1
};
And I am getting these states
signalingState: stable
iceConnectionState: new
iceGatheringState: new
also "remoteDescription" and "localDescription" are set
This error typically suggests that no remote description was set and this is not shown in the message from the server. See here on how to use chrome's webrtc-internals page for debugging.

Login Google javascript

I´m using google login javascript.
I want import js after click button. The problem: Only show popup login google the second time I click the button
My Code:
function clickButton(){
$.getScript( "https://apis.google.com/js/client:plusone.js?onload=onLoadGoogleLogin");
}
function onLoadGoogleLogin()
{
var initializedGoogleCallback = false;
gapi.client.setApiKey('AIzaSyBhV6vP_D_I7ldL1YIU7LJUGtSxJ55ievw');
var myParams = {
'callback': function googleLoginCallback(result) {
debugger;
if (!initializedGoogleCallback) {
if (result) {
if (result['error'] == undefined) {
initializedGoogleCallback = true;
gapi.auth.setToken(result);
gapi.client.load('oauth2', 'v2', function () {
var request = gapi.client.oauth2.userinfo.get();
request.execute(googleLoginDataUserCallback);
});
}
} else {
alert('Empty authResult');
}
}
},
'clientid': 'xxxxx-4kragpsm6jolann6d9t74crpkthch0iq.apps.googleusercontent.com',
'cookiepolicy': 'single_host_origin',
'requestvisibleactions': 'http://schemas.google.com/AddActivity',
'scope': 'https://www.googleapis.com/auth/plus.login'
}

Opening and accessing a pop up window in chrome extension

Hi I need to know how to access contents of a pop up window in chrome extension.Presently I have set my website as chrome extension.What I need is that when I install the extension a pop up window should be opened asking for username and password.When the user enters his username and password it should gets stored in a local Storage.Currently I am able to open a pop up window.But I don't know how to store the name which the user enters as username.Anyone please help me.I can't figure out how to do it.
Here is manifest.json
{
"name": "Calpine Extension",
"version": "1.0",
"description": "Log on to calpinemate",
"manifest_version": 2,
"browser_action": {
"default_icon": "icon_128.png"
},
"background": {
"persistent": false,
"scripts": ["background.js"]
},
"browser_action": {
"default_title": "Test Extension",
"default_icon": "calpine_not_logged_in.png"
},
"permissions": [
"*://blog.calpinetech.com/test/index.php",
"alarms",
"notifications"
],
"web_accessible_resources": [
"/icon_128.png"]
}
Here is background.js
var myNotificationID = null;
var oldChromeVersion = !chrome.runtime;
function getGmailUrl() {
return "http://calpinemate.com/";
}
function isGmailUrl(url) {
return url.indexOf(getGmailUrl()) == 0;
}
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.query({
url: "http://calpinemate.com/*",
currentWindow: true
},
function(tabs) {
if (tabs.length > 0) {
var tab = tabs[0];
console.log("Found (at least one) Gmail tab: " + tab.url);
console.log("Focusing and refreshing count...");
chrome.tabs.update(tab.id, { active: true });
updateIcon();
}
else {
console.log("Could not find Gmail tab. Creating one...");
chrome.tabs.create({ url: getGmailUrl() });
updateIcon();
}
});
});
function onInit() {
console.log('onInit');
updateIcon();
if (!oldChromeVersion) {
chrome.alarms.create('watchdog', {periodInMinutes:5});
}
}
function onAlarm(alarm) {
console.log('Got alarm', alarm);
if (alarm && alarm.name == 'watchdog') {
onWatchdog();
}
else {
updateIcon();
}
}
function onWatchdog() {
chrome.alarms.get('refresh', function(alarm) {
if (alarm) {
console.log('Refresh alarm exists. Yay.');
}
else {
console.log('Refresh alarm doesn\'t exist!? ' +
'Refreshing now and rescheduling.');
updateIcon();
}
});
}
if (oldChromeVersion) {
updateIcon();
onInit();
}
else {
chrome.runtime.onInstalled.addListener(onInit);
chrome.alarms.onAlarm.addListener(onAlarm);
}
function updateIcon(){
var req = new XMLHttpRequest();
req.addEventListener("readystatechange", function() {
if (req.readyState == 4) {
if (req.status == 200) {
var item=req.responseText;
if(item==1){
chrome.browserAction.setIcon({path:"calpine_logged_in.png"});
chrome.browserAction.setBadgeBackgroundColor({color:[190, 190, 190, 230]});
chrome.browserAction.setBadgeText({text:""});
}
else{
chrome.browserAction.setIcon({path:"calpine_not_logged_in.png"});
chrome.browserAction.setBadgeBackgroundColor({color:[190, 190, 190, 230]});
chrome.browserAction.setBadgeText({text:""});
chrome.notifications.create(
'id1',{
type: 'basic',
iconUrl: '/icon_128.png',
title: 'Calpinemate',
message: 'Hello calpiner',
buttons: [{ title: 'Mark',
iconUrl: '/tick.jpg'
},{ title: 'Ignore',
iconUrl: '/cross.jpg'}],
priority: 0},
function(id) { myNotificationID = id;}
);
chrome.notifications.onButtonClicked.addListener(function(notifId, btnIdx) {
if (notifId === myNotificationID) {
if (btnIdx === 0) {
window.open("http://www.calpinemate.com/");
} else if (btnIdx === 1) {
notification.close();
}
}
});
chrome.notifications.onClosed.addListener(function() {
notification.close();
});
}
}
else {
// Handle the error
alert("ERROR: status code " + req.status);
}
}
});
req.open("GET", "http://blog.calpinetech.com/test/index.php", true);
req.send(null);
}
function login() {
/* First retrieve the credentials */
chrome.storage.local.get(['username', 'password'], function(items) {
var user = items.username;
var pass = items.password;
if (!user || !pass) {
/* Missing credentials. Prompt the user. */
chrome.windows.create({ url : "test.html" });
return;
}
/* Log-in */
// ...code that logs the user in
});
}
Here is test.html
<html>
<head>
<script type="text/javascript">
function log(){
var uname=document.getElementById('name');
document.getElementById('pp').innerHTML = uname;
}
</script>
</head>
<body>
<form name="userinfo" id="userinfo">
username :
<input id="name" type="text" name="username"/><br><br>
password :
<input type="password" name="password"/><br><br>
<input type="button" value="Log In" onclick="log()"/>
<p id="pp"></p>
</form>
</body>
</html>
test.js
window.addEventListener('DOMContentLoaded', function() {
var user = document.querySelector('input#user');
var pwd = document.querySelector('input#pass');
var form = document.querySelector('form#userinfo');
form.addEventListener('submit', function(evt) {
evt.preventDefault();
var userStr = user.value;
var pwdStr = pwd.value;
if ((userStr.length === 0) || (passStr.length === 0)) {
alert('Please, specify both Username and Password !');
return;
}
chrome.runtime.getBackgroundPage(function(bgPage) {
bgPage.login(userStr,pwdStr); });
window.close();
});
});
Due to the Content Security Policy (CSP), inline scripts won't be executed. You should move the code and the event bindings to an external JS file and use the chrome.storage API to store the username and password.
In test.html:
<html>
<head>
<script type="text/javascript" src="test.js"></script>
</head>
<body>
<form id="userinfo">
<label for="user">Username:</label>
<input type="text" id="user" />
<br />
<label for="pass">Password:</label>
<input type="password" id="pass" />
<br />
<br />
<input type="button" id="login" value="Log In" />
</form>
</body>
</html>
In test.js:
window.addEventListener('DOMContentLoaded', function() {
var user = document.querySelector('input#user');
var pass = document.querySelector('input#pass');
var login = document.querySelector('input#login');
login.addEventListener('click', function() {
var userStr = user.value;
var passStr = pass.value;
/* Validate input */
if ((userStr.length === 0) || (passStr.length === 0)) {
alert('Please, specify both Username and Password !');
return;
}
/* Store the data */
chrome.storage.local.set({
username: userStr,
password: passStr,
}, function() {
if (chrome.runtime.lastError) {
/* An error occurred. Unable to proceed. */
// ...handle the error, e.g. inform the user
return;
}
/* Do whatever youneed to, e.g. log-in the user */
chrome.runtime.getBackgroundPage(function(bgPage) {
bgPage.login();
});
});
});
});
In background.js:
...
function login() {
/* First retrieve the credentials */
chrome.storage.local.get(['username', 'password'], function(items) {
var user = items.username;
var pass = items.password;
if (!user || !pass) {
/* Missing credentials. Prompt the user. */
chrome.windows.create({ url : "test.html" });
return;
}
/* Log-in */
// ...code that logs the user in
});
}
(Using chrome.storage.sync (instead of .local) will sync the data across the user's devices if (s)he enables that option from the account settings.)
Please, note:
Confidential user information should not be stored! The storage area isn't encrypted.

Categories

Resources