I've got some javascript code in an application that automatically requests through an iframe and hardcoded credentials an id_token and access_token to an openid connect/oauth2 endpoint.
The problem is that, although the user does not get to see the form because it happens silently, google smart lock prompts the user to save the credentials, which is undesirable (mainly because they are hardcoded and don't need to be remembered, and because we don't want users to see this).
Is there any way to prevent from code to google smart lock from displaying or any workaround to avoid this?
This is the code that gets executed with the hardcoded credentials.
TokenManager.prototype.login = function(username, password, rememberMe) {
var mgr = this;
var formHtml = '<form name="form" id="loginForm" method="post" style="display: none"></form>';
var form = $(formHtml).appendTo("body");
form.attr("action", this.settings.loginUrl + '?signin=' + this.signinId());
form.attr("target", this.settings.frameName);
var a = $('<input name="idsrv.xsrf" type="hidden">').appendTo(form);
var u = $('<input name="username" id="username" type="text">').appendTo(form);
var p = $('<input id="password" name="password" type="password">').appendTo(form);
var r = $('<input type="checkbox" id="rememberMe" name="rememberMe">').appendTo(form);
var btn = $('<button type="submit" style="display: none"></button>').appendTo(form);
u.val(username);
p.val(password);
r.val(rememberMe);
var checked = '';
if (rememberMe) {
checked = 'checked';
}
r.attr('checked', checked);
a.val(getCookie(TokenManager.xsrfKey));
var oauth = new OAuthClient(this.settings);
var frame = new FrameLoader('', this.settings.frameName);
frame.load(function (data) {
form.remove();
if (data.type === 'login') {
setCookie(TokenManager.xsrfKey, data.model.antiForgery.value, 1);
setCookie(TokenManager.signInKey, data.signin, 1);
this.showLogin(data.model, username);
} else
if (data.type === 'tokenCallback') {
var result = oauth.readImplicitResult(data.hash);
if (!result.error) {
var token = Token.fromOAuthResponse(result);
this.saveToken(token);
this.callTokenObtained();
}
} else {
if (data.type === 'error') {
var request = oauth.createImplicitRequest();
frame = new FrameLoader(request.url, mgr.settings.frameName);
frame.load(function(d) {
if (d.type === 'login') {
setCookie(TokenManager.signInKey, d.signin, 1);
setCookie(TokenManager.xsrfKey, data.model.antiForgery.value, 1);
setTimeout(function() {
mgr.login(username, password, rememberMe);
}, 0);
} else
if (d.type === 'tokenCallback') {
var result = oauth.readImplicitResult(d.hash);
if (!result.error) {
var token = Token.fromOAuthResponse(result);
mgr.saveToken(token);
mgr.callTokenObtained();
}
}
});
}
}
}.bind(this), function() {});
btn.click();
}
and this is the FrameLoader.js that is being used
define(['jquery'], function ($) {
function FrameLoader(url, frameName) {
this.url = url;
this.frameName = frameName;
}
FrameLoader.prototype.load = function(success, error) {
var frameHtml = '<iframe name="' + this.frameName + '" style="display:none"></iframe>';
var frame = $(frameHtml).appendTo("body");
function cleanup() {
window.removeEventListener("message", message, false);
if (handle) {
window.clearTimeout(handle);
}
handle = null;
frame.remove();
}
function cancel(e) {
cleanup();
if (error) {
error();
}
}
function message(e) {
if (handle && e.origin === location.protocol + "//" + location.host) {
cleanup();
if (success) {
success(e.data);
}
}
}
var handle = window.setTimeout(cancel, 10000);
window.addEventListener("message", message, false);
if (this.url)
frame.attr("src", this.url);
};
return FrameLoader;
});
Related
I'm using the TomTom FuzzySearch/Autocomplete API, to allow users to search for an address on a form and then the address input fields will prepopulate (with the address values), when the user selects an address.
My API call works absolutely fine and the input fields display the correct values.
The problem I have, is the input fields remain untouched, despite the fields having a value. (If I type document.getElementById("house-number-textbox").value, a value is returned).
How can I turned the input fields to be touched, when the input values are applied?
I noticed, if I type something in the input field, after my input values have been added, only then does the form register my inputs as valid/touched.
PS - The reason I am injecting my scripts is because I'm using an AB Testing tool. So despite the form/application being AngularJS, I can only manipulate the form via the AB Testing tool, (on top of the compiled codebase - hence why I'm using vanilla JS).
Here's my code:
function waitForElement(className, callBack){
window.setTimeout(function(){
var element = document.getElementById(className);
if(element) {
callBack(className, element);
} else {
waitForElement(className, callBack);
}
},2000)
};
// LOAD API SCRIPTS
function loadScript(scriptUrl) {
const script = document.createElement('script');
script.src = scriptUrl;
document.body.appendChild(script);
return new Promise((res, rej) => {
script.onload = function() {
res();
}
script.onerror = function () {
rej();
}
});
};
// RESULTS MANAGER
function appendParentSelector(parentSelector, selector) {
return parentSelector ? parentSelector + ' ' + selector : selector;
}
function ResultsManager(resultsElementSelector) {
this.resultsElement = document.querySelector(appendParentSelector(resultsElementSelector, '.js-results'));
this.resultsPlaceholder =
document.querySelector(appendParentSelector(resultsElementSelector, '.js-results-placeholder'));
this.resultsLoader = document.querySelector(appendParentSelector(resultsElementSelector, '.js-results-loader'));
}
ResultsManager.prototype.loading = function() {
this.resultsLoader.removeAttribute('hidden');
this.resultsElement.setAttribute('hidden', 'hidden');
this.resultsPlaceholder.setAttribute('hidden', 'hidden');
this.resultsElement.innerHTML = '';
};
ResultsManager.prototype.success = function() {
this.resultsLoader.setAttribute('hidden', 'hidden');
this.resultsElement.removeAttribute('hidden');
};
ResultsManager.prototype.resultsNotFound = function() {
this.resultsElement.setAttribute('hidden', 'hidden');
this.resultsLoader.setAttribute('hidden', 'hidden');
this.resultsPlaceholder.removeAttribute('hidden');
};
ResultsManager.prototype.append = function(element) {
this.resultsElement.appendChild(element);
};
ResultsManager.prototype.clear = function() {
for (var i = 0; i < this.resultsElement.children.length; i++) {
this.resultsElement.removeChild(this.resultsElement.children[i]);
}
};
waitForElement("house-number-textbox",function(){
console.log("WAIT FOR ELEMENT DONE");
window.ResultsManager = window.ResultsManager || ResultsManager;
console.log("document.getElementById(component)", document.getElementById("house-number-textbox") );
// use
loadScript('https://api.tomtom.com/maps-sdk-for-web/cdn/plugins/SearchBox/2.24.2//SearchBox-web.js')
.then(() => {
console.log('Script loaded!');
})
.catch(() => {
console.error('Script loading failed! Handle this error');
});
// use
loadScript('https://api.tomtom.com/maps-sdk-for-web/cdn/5.x/5.64.0/services/services-web.min.js')
.then(() => {
console.log('Script loaded!');
// HANDLE RESULTS
tt.setProductInfo('ABTest', '1');
// Options for the fuzzySearch service
var searchOptions = {
key: 'XXX',
language: 'en-Gb',
limit: 10,
countrySet: "GB"
};
var searchBoxOptions = {
minNumberOfCharacters: 1,
searchOptions: searchOptions
// autocompleteOptions: autocompleteOptions
};
var ttSearchBox = new tt.plugins.SearchBox(tt.services, searchBoxOptions);
document.querySelector('.tt-side-panel__header').appendChild(ttSearchBox.getSearchBoxHTML());
let componentForm = {
// streetName: "house-number-textbox",
municipalitySubdivision: "street-name-textbox",
localName: "town-city-textbox",
extendedPostalCode: "postcode-textbox"
};
function SidePanel(selector) {
// this.map = map;
this.element = document.querySelector(selector);
}
new SidePanel('.tt-side-panel');
var resultsManager = new ResultsManager();
ttSearchBox.on('tomtom.searchbox.resultscleared', handleResultsCleared);
ttSearchBox.on('tomtom.searchbox.resultsfound', handleResultsFound);
ttSearchBox.on('tomtom.searchbox.resultfocused', handleResultSelection);
ttSearchBox.on('tomtom.searchbox.resultselected', handleResultSelection);
function handleResultsCleared() {
resultsManager.clear();
}
// HANDLE RESULST
function handleResultsFound(event) {
// Display fuzzySearch results if request was triggered by pressing enter
if (event.data.results && event.data.results.fuzzySearch && event.data.metadata.triggeredBy === 'submit') {
var results = event.data.results.fuzzySearch.results;
if (results.length === 0) {
handleNoResults();
}
resultsManager.success();
console.log("results", results);
}
if (event.data.errors) {
console("event.data.errors", event.data.errors);
}
}
// RESPONSE
function handleResultSelection(event) {
if (isFuzzySearchResult(event)) {
// Display selected result on the map
var result = event.data.result;
console.log("THIS result", result);
;
resultsManager.success();
for (const component in componentForm) {
console.log("componentForm", componentForm);
document.getElementById(componentForm[component]).value = result.address[component];
document.getElementById(componentForm[component]).disabled = false;
console.log('component', componentForm[component]);
if (document.getElementById(componentForm[component]).value === 'undefined') {
document.getElementById(componentForm[component]).value = "";
}
};
if (result.address.streetNumber) {
document.getElementById("house-number-textbox").value = result.address.streetNumber + " " + result.address.streetName;
} else {
document.getElementById("house-number-textbox").value = result.address.streetName;
};
};
}
function isFuzzySearchResult(event) {
return !('matches' in event.data.result);
}
function handleNoResults() {
resultsManager.clear();
resultsManager.resultsNotFound();
searchMarkersManager.clear();
infoHint.setMessage(
'No results for "' +
ttSearchBox.getValue() +
'" found nearby. Try changing the viewport.'
);
};
document.querySelector(".tt-search-box-input").setAttribute("placeholder", "Enter your address...");
})
.catch(() => {
console.error('Script loading failed! Handle this error');
});
});
I have found quite a few similar qustions but they are mainly old and outdated and some of them provided a few pointers which I followed to no avail.
Basically, I'm tring to use webrtc and the phonegap iosrtc plugin to create a simple 2 way video chat.
I followed everything to the letter and I managed to show my own video in the app but the 'remote' video is not showing and I ant figure out what the issue is at all!
I have enabled the debugging in phonegap but I don't get any errors.
This is my complete code:
HTML:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://rtcmulticonnection.herokuapp.com/dist/RTCMultiConnection.min.js"></script>
<script src="https://rtcmulticonnection.herokuapp.com/node_modules/webrtc-adapter/out/adapter.js"></script>
<script src="https://rtcmulticonnection.herokuapp.com/socket.io/socket.io.js"></script>
<!-- custom layout for HTML5 audio/video elements -->
<link rel="stylesheet" href="https://rtcmulticonnection.herokuapp.com/dev/getHTMLMediaElement.css">
<script src="https://rtcmulticonnection.herokuapp.com/dev/getHTMLMediaElement.js"></script>
<script src="https://rtcmulticonnection.herokuapp.com/node_modules/recordrtc/RecordRTC.js"></script>
<script src="cordova.js"></script>
<script src="ios-websocket-hack.js"></script>
<section class="make-center">
<div>
<label><input type="checkbox" id="record-entire-conference"> Record Entire Conference In The Browser?</label>
<span id="recording-status" style="display: none;"></span>
<button id="btn-stop-recording" style="display: none;">Stop Recording</button>
<br><br>
<input type="text" id="room-id" value="abcdef" autocorrect=off autocapitalize=off size=20>
<button id="open-room">Open Room</button>
<button id="join-room">Join Room</button>
<button id="open-or-join-room">Auto Open Or Join Room</button>
</div>
<div id="videos-container" style="margin: 20px 0;"></div>
<div id="room-urls" style="text-align: center;display: none;background: #F1EDED;margin: 15px -10px;border: 1px solid rgb(189, 189, 189);border-left: 0;border-right: 0;"></div>
</section>
JAVASCRIPT:
// ......................................................
// .......................UI Code........................
// ......................................................
document.getElementById('open-room').onclick = function() {
disableInputButtons();
connection.open(document.getElementById('room-id').value, function(isRoomOpened, roomid, error) {
if(isRoomOpened === true) {
showRoomURL(connection.sessionid);
}
else {
disableInputButtons(true);
if(error === 'Room not available') {
alert('Someone already created this room. Please either join or create a separate room.');
return;
}
alert(error);
}
});
};
document.getElementById('join-room').onclick = function() {
disableInputButtons();
connection.join(document.getElementById('room-id').value, function(isJoinedRoom, roomid, error) {
if (error) {
disableInputButtons(true);
if(error === 'Room not available') {
alert('This room does not exist. Please either create it or wait for moderator to enter in the room.');
return;
}
alert(error);
}
});
};
document.getElementById('open-or-join-room').onclick = function() {
disableInputButtons();
connection.openOrJoin(document.getElementById('room-id').value, function(isRoomExist, roomid, error) {
if(error) {
disableInputButtons(true);
alert(error);
}
else if (connection.isInitiator === true) {
// if room doesn't exist, it means that current user will create the room
showRoomURL(roomid);
}
});
};
// ......................................................
// ..................RTCMultiConnection Code.............
// ......................................................
var connection = new RTCMultiConnection();
// by default, socket.io server is assumed to be deployed on your own URL
//connection.socketURL = '/';
// comment-out below line if you do not have your own socket.io server
connection.socketURL = 'https://rtcmulticonnection.herokuapp.com:443/';
connection.socketMessageEvent = 'video-conference-demo';
connection.session = {
audio: true,
video: true
};
connection.sdpConstraints.mandatory = {
OfferToReceiveAudio: true,
OfferToReceiveVideo: true
};
connection.videosContainer = document.getElementById('videos-container');
connection.onstream = function(event) {
var existing = document.getElementById(event.streamid);
if(existing && existing.parentNode) {
existing.parentNode.removeChild(existing);
}
/*event.mediaElement.removeAttribute('src');
event.mediaElement.removeAttribute('srcObject');
event.mediaElement.muted = true;
event.mediaElement.volume = 0;*/
var video = document.createElement('video');
try {
video.setAttributeNode(document.createAttribute('autoplay'));
video.setAttributeNode(document.createAttribute('playsinline'));
} catch (e) {
video.setAttribute('autoplay', true);
video.setAttribute('playsinline', true);
}
if(event.type === 'local') {
video.setAttribute('class', 'myvideo');
//$('.yourVideo').attr('src', event.stream);
//$('.yourVideo').attr('id', event.streamid);
alert('local');
video.volume = 0;
try {
video.setAttributeNode(document.createAttribute('muted'));
} catch (e) {
video.setAttribute('muted', true);
}
}
if (event.type === 'remote') {
alert('remote');
video.setAttribute('class', 'othersvideo');
}
video.src = URL.createObjectURL(event.stream);
//var width = parseInt(connection.videosContainer.clientWidth / 3) - 20;
var width = $(document).width();
var height = $(document).height();
var mediaElement = getHTMLMediaElement(video, {
/*title: event.userid,*/
buttons: ['full-screen'],
width: 100,
height: 100,
showOnMouseEnter: false
});
connection.videosContainer.appendChild(mediaElement);
setTimeout(function() {
// mediaElement.media.play();
video.play();
}, 5000);
mediaElement.id = event.streamid;
// to keep room-id in cache
localStorage.setItem(connection.socketMessageEvent, connection.sessionid);
chkRecordConference.parentNode.style.display = 'none';
if(chkRecordConference.checked === true) {
btnStopRecording.style.display = 'inline-block';
recordingStatus.style.display = 'inline-block';
var recorder = connection.recorder;
if(!recorder) {
recorder = RecordRTC([event.stream], {
type: 'video'
});
recorder.startRecording();
connection.recorder = recorder;
}
else {
recorder.getInternalRecorder().addStreams([event.stream]);
}
if(!connection.recorder.streams) {
connection.recorder.streams = [];
}
connection.recorder.streams.push(event.stream);
recordingStatus.innerHTML = 'Recording ' + connection.recorder.streams.length + ' streams';
}
if(event.type === 'local') {
connection.socket.on('disconnect', function() {
if(!connection.getAllParticipants().length) {
location.reload();
}
});
}
};
var recordingStatus = document.getElementById('recording-status');
var chkRecordConference = document.getElementById('record-entire-conference');
var btnStopRecording = document.getElementById('btn-stop-recording');
btnStopRecording.onclick = function() {
var recorder = connection.recorder;
if(!recorder) return alert('No recorder found.');
recorder.stopRecording(function() {
var blob = recorder.getBlob();
invokeSaveAsDialog(blob);
connection.recorder = null;
btnStopRecording.style.display = 'none';
recordingStatus.style.display = 'none';
chkRecordConference.parentNode.style.display = 'inline-block';
});
};
connection.onstreamended = function(event) {
var mediaElement = document.getElementById(event.streamid);
if (mediaElement) {
mediaElement.parentNode.removeChild(mediaElement);
}
};
connection.onMediaError = function(e) {
if (e.message === 'Concurrent mic process limit.') {
if (DetectRTC.audioInputDevices.length <= 1) {
alert('Please select external microphone. Check github issue number 483.');
return;
}
var secondaryMic = DetectRTC.audioInputDevices[1].deviceId;
connection.mediaConstraints.audio = {
deviceId: secondaryMic
};
connection.join(connection.sessionid);
}
};
// ..................................
// ALL below scripts are redundant!!!
// ..................................
function disableInputButtons(enable) {
document.getElementById('room-id').onkeyup();
document.getElementById('open-or-join-room').disabled = !enable;
document.getElementById('open-room').disabled = !enable;
document.getElementById('join-room').disabled = !enable;
document.getElementById('room-id').disabled = !enable;
}
// ......................................................
// ......................Handling Room-ID................
// ......................................................
function showRoomURL(roomid) {
var roomHashURL = '#' + roomid;
var roomQueryStringURL = '?roomid=' + roomid;
var html = '<h2>Unique URL for your room:</h2><br>';
html += 'Hash URL: ' + roomHashURL + '';
html += '<br>';
html += 'QueryString URL: ' + roomQueryStringURL + '';
var roomURLsDiv = document.getElementById('room-urls');
roomURLsDiv.innerHTML = html;
roomURLsDiv.style.display = 'block';
}
(function() {
var params = {},
r = /([^&=]+)=?([^&]*)/g;
function d(s) {
return decodeURIComponent(s.replace(/\+/g, ' '));
}
var match, search = window.location.search;
while (match = r.exec(search.substring(1)))
params[d(match[1])] = d(match[2]);
window.params = params;
})();
var roomid = '';
if (localStorage.getItem(connection.socketMessageEvent)) {
roomid = localStorage.getItem(connection.socketMessageEvent);
} else {
roomid = connection.token();
}
var txtRoomId = document.getElementById('room-id');
txtRoomId.value = roomid;
txtRoomId.onkeyup = txtRoomId.oninput = txtRoomId.onpaste = function() {
localStorage.setItem(connection.socketMessageEvent, document.getElementById('room-id').value);
};
var hashString = location.hash.replace('#', '');
if (hashString.length && hashString.indexOf('comment-') == 0) {
hashString = '';
}
var roomid = params.roomid;
if (!roomid && hashString.length) {
roomid = hashString;
}
if (roomid && roomid.length) {
document.getElementById('room-id').value = roomid;
localStorage.setItem(connection.socketMessageEvent, roomid);
// auto-join-room
(function reCheckRoomPresence() {
connection.checkPresence(roomid, function(isRoomExist) {
if (isRoomExist) {
connection.join(roomid);
return;
}
setTimeout(reCheckRoomPresence, 5000);
});
})();
disableInputButtons();
}
// detect 2G
if(navigator.connection &&
navigator.connection.type === 'cellular' &&
navigator.connection.downlinkMax <= 0.115) {
alert('2G is not supported. Please use a better internet service.');
}
window.cordova.InAppBrowser.open(" https://vps267717.ovh.net/webrtc", "_blank", "location=no,toolbar=yes");
As you can see in my code, I have this:
if (event.type === 'remote') {
alert('remote');
video.setAttribute('class', 'othersvideo');
}
But this never fires for some reason!
I have spent the last 3 days trying to figure this out but I haven't had any luck.
So any help and advice would be appreciated.
Thanks in advance.
In my site, I have a form that users can click on a checkbox to select "available". I want to have "Yes" or "No" returned in the displayArticle function based on whether the box is checked or not. Right now it returns True or False, which is not optimal. How can I code this?
Here is my entire JS code:
App = {
web3Provider: null,
contracts: {},
account: 0x0,
loading: false,
init: function() {
return App.initWeb3();
},
initWeb3: function() {
// initialize web3
if(typeof web3 !== 'undefined') {
//reuse the provider of the Web3 object injected by Metamask
App.web3Provider = web3.currentProvider;
} else {
//create a new provider and plug it directly into our local node
App.web3Provider = new Web3.providers.HttpProvider('http://localhost:7545');
}
web3 = new Web3(App.web3Provider);
App.displayAccountInfo();
return App.initContract();
},
displayAccountInfo: function() {
web3.eth.getCoinbase(function(err, account) {
if(err === null) {
App.account = account;
$('#account').text(account);
web3.eth.getBalance(account, function(err, balance) {
if(err === null) {
$('#accountBalance').text(web3.fromWei(balance, "ether") + " ETH");
}
})
}
});
},
initContract: function() {
$.getJSON('RentalContract.json', function(chainListArtifact) {
//added May24 to json file name
// get the contract artifact file and use it to instantiate a truffle contract abstraction
App.contracts.RentalContract = TruffleContract(chainListArtifact);
// set the provider for our contracts
App.contracts.RentalContract.setProvider(App.web3Provider);
// listen to events
App.listenToEvents();
// retrieve the article from the contract
return App.reloadArticles();
});
},
reloadArticles: function() {
//avoid reentry bugs
if(App.loading){
return;
}
App.loading = true;
// refresh account information because the balance might have changed
App.displayAccountInfo();
var chainListInstance;
App.contracts.RentalContract.deployed().then(function(instance) {
chainListInstance = instance;
return chainListInstance.getArticlesForSale();
}).then(function(articlesIds) {
// retrieve the article placeholder and clear it
$('#articlesRow').empty();
for(var i = 0; i < articlesIds.length; i++){
var articleId = articlesIds[i];
chainListInstance.articles(articleId.toNumber()).then(function(article){
App.displayArticle(article[0], article[1], article[3], article[4], article[5], article[6], article[7]);
});
}
App.loading = false;
}).catch(function(err) {
console.error(err.message);
App.loading = false;
});
},
//displayArticle: function(id, seller, beds, baths, propaddress, rental_price, property_type, description, available, contact_email) {
displayArticle: function(id, seller, propaddress, rental_price, description, available, contact) {
var articlesRow = $('#articlesRow');
//var etherPrice = web3.fromWei(price, "ether");
var articleTemplate = $("#articleTemplate");
//articleTemplate.find('.panel-title').text(propaddress);
//articleTemplate.find('.beds').text(beds);
//articleTemplate.find('.baths').text(baths);
articleTemplate.find('.propaddress').text(propaddress);
articleTemplate.find('.rental_price').text('$' + rental_price);
//articleTemplate.find('.property_type').text(property_type);
articleTemplate.find('.description').text(description);
articleTemplate.find('.available').text(available);
articleTemplate.find('.contact').text(contact);
// articleTemplate.find('.article_price').text(etherPrice + " ETH");
articleTemplate.find('.btn-buy').attr('data-id', id);
// articleTemplate.find('.btn-buy').attr('data-value', etherPrice);
//seller
if(seller == App.account){
articleTemplate.find('.article-seller').text("You");
articleTemplate.find('.btn-buy').hide();
}else{
articleTemplate.find('.article-seller').text(seller);
articleTemplate.find('.btn-buy').show();
}
//add this new article
articlesRow.append(articleTemplate.html());
},
sellArticle: function() {
// retrieve the detail of the article
// var _article_name = $('#article_name').val();
var _description = $('#description').val();
//var _beds = $('#beds').val();
//var _baths = $('#baths').val();
var _propaddress = $('#propaddress').val();
var _rental_price = $('#rental_price').val();
//var _property_type = $('#property_type').val();
var _available = $('#available').val();
var _contact = $('#contact').val();
// var _article_price = $('#article_price').val();
// var _price = web3.toWei(parseFloat($('#article_price').val() || 0), "ether");
// if((_description.trim() == '') || (rental_price == 0)) {
// nothing to sell
// return false;
// }
App.contracts.RentalContract.deployed().then(function(instance) {
//return instance.sellArticle(_description, _beds, _baths, _propaddress, _rental_price, _property_type, _available, _contact_email, {
return instance.sellArticle(_propaddress, _rental_price, _description, _available, _contact,{
from: App.account,
gas: 500000
});
}).then(function(result) {
}).catch(function(err) {
console.error(err);
});
},
// listen to events triggered by the contract
listenToEvents: function() {
App.contracts.RentalContract.deployed().then(function(instance) {
instance.LogSellArticle({}, {}).watch(function(error, event) {
if (!error) {
$("#events").append('<li class="list-group-item">' + event.args._propaddress + ' is now for sale</li>');
} else {
console.error(error);
}
App.reloadArticles();
});
instance.LogBuyArticle({}, {}).watch(function(error, event) {
if (!error) {
$("#events").append('<li class="list-group-item">' + event.args._buyer + ' bought ' + event.args._propaddress + '</li>');
} else {
console.error(error);
}
App.reloadArticles();
});
});
},
buyArticle: function() {
event.preventDefault();
// retrieve the article price and data
var _articleId = $(event.target).data('id');
var _price = parseFloat($(event.target).data('value'));
App.contracts.RentalContract.deployed().then(function(instance){
return instance.buyArticle(_articleId, {
from: App.account,
value: web3.toWei(_price, "ether"),
gas: 500000
});
}).catch(function(error) {
console.error(error);
});
}
};
$(function() {
$(window).load(function() {
App.init();
});
});
If I understand what you're trying to do, perhaps this will work for you.
var isChecked = '';
if (articleTemplate.find('.available').checked === true)
{ isChecked = 'yes'} else
{ isChecked = 'no'}
.
.
.
return isChecked;
Do this:
articleTemplate.find( '.available' ).text( available ? 'Yes' : 'No' );
Example:
function returnValue() {
$( '#val' ).text( $( '#chk' ).is( ':checked' ) ? 'Yes' : 'No' )
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="chk" onclick="returnValue()" />
<label for="chk">Available</label>
<h2 id="val"></h2>
The case:
I have a simple cordova app that opens the mobile version of a (Drupal 7) website using the inAppBrowser plugin. On the website, a user can log in to read more content. Also everyone that has the app installed, can get push notifications if accepted.
The problem: Users who have logged in are being logged out after a while. It happens on both iOS and Android.
Now I would like is that the app stores the filled in value of the username and password. So when the user is being logged out it has it's credentials filled in. Is anyone able to help?
I have found a few similar question on the web, but I can't seem to get it to work using localStorage.
This is a snippet I found in this question. But I can't get it to work. the edit-name and edit-pass are the id's of the input fields on the website.
function loadStopped() {
var username = "";
if (localStorage.getItem("username") !== null) {
username = localStorage.getItem("username");
}
var password = "";
if (localStorage.getItem("password") !== null) {
password = localStorage.getItem("password");
}
document.getElementById("edit-name").value = username;
document.getElementById("edit-pass").value = password;
document.getElementById("the_form").addEventListener("submit", function() {
localStorage.setItem("username", document.getElementById("edit-name").value);
localStorage.setItem("password", document.getElementById("edit-pass").value);
});
}
My full code:
var app = {
// Application Constructor
browser: null,
host: 'http://www.somewebsite.com/',
initialize: function () {
this.bindEvents();
},
// Bind Event Listeners
bindEvents: function () {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
// deviceready Event Handler
onDeviceReady: function () {
app.checkConnection();
app.initPushwoosh();
},
checkConnection: function () {
var networkState = navigator.connection.type;
var states = {};
states[Connection.NONE] = 'no connection';
//if no connection show popup
if (networkState === Connection.NONE) {
navigator.notification.alert(
'Please enable your internet connection\nand restart the app', // message
function () {
}, // callback
'Oops no internet', // title
'Ok' // buttonName
);
//if network is found, launch inappbrowser
} else {
app.openBrowser('/');
}
},
openBrowser: function (url) {
function loadStopped() {
var username = "";
if (localStorage.getItem("username") !== null) {
username = localStorage.getItem("username");
}
var password = "";
if (localStorage.getItem("password") !== null) {
password = localStorage.getItem("password");
}
document.getElementById("edit-name").value = username;
document.getElementById("edit-pass").value = password;
document.getElementById("the_form").addEventListener("submit", function() {
localStorage.setItem("username", document.getElementById("edit-name").value);
localStorage.setItem("password", document.getElementById("edit-pass").value);
});
}
if (url.indexOf('/') !== 0) {
url = '/' + url;
}
url = this.updateQueryStringParameter(url, 'app_os', 'mobile');
window.open = cordova.InAppBrowser.open;
this.browser = cordova.InAppBrowser.open(this.host + url, '_blank', 'location=no,hidden=no');
this.browser.addEventListener('loadstop', loadstopped);
this.browser.addEventListener('loadstop', function(e)){
var username="";
if (localStorage.getItem("username") !== null){
username = localStorage.getItem("username");
}
this.browser.executeScript({
code:"document.getElementById('edit-name').value;"
});
});
this.browser.addEventListener('exit', function (e) {
if (navigator.app) {
navigator.app.exitApp();
} else if (navigator.device) {
navigator.device.exitApp();
} else {
window.close();
}
});
},
// Update DOM on a Received Event
receivedEvent: function (id) {
var parentElement = document.getElementById(id);
var listeningElement = parentElement.querySelector('.listening');
var receivedElement = parentElement.querySelector('.received');
listeningElement.setAttribute('style', 'display:none;');
receivedElement.setAttribute('style', 'display:block;');
console.log('Received Event: ' + id);
},
updateQueryStringParameter: function(uri, key, value) {
// remove the hash part before operating on the uri
var i = uri.indexOf('#');
var hash = i === -1 ? '' : uri.substr(i);
uri = i === -1 ? uri : uri.substr(0, i);
var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
var separator = uri.indexOf('?') !== -1 ? "&" : "?";
if (!value) {
// remove key-value pair if value is empty
uri = uri.replace(new RegExp("([&]?)" + key + "=.*?(&|$)", "i"), '');
if (uri.slice(-1) === '?') {
uri = uri.slice(0, -1);
}
} else if (uri.match(re)) {
uri = uri.replace(re, '$1' + key + "=" + value + '$2');
} else {
uri = uri + separator + key + "=" + value;
}
return uri + hash;
}
};
app.initialize();
Anyone who could tell me what I'm doing wrong or can give me a detailed 'guide' of how I can get it to work?
Thanks a lot in advance!
It's simple validation module. Now, i can't understand why my functions (validateEmail) can't call successful. I have no js errors, but browser do postback with my form thorought validation code
<script type="text/javascript">
var Validation;
(function (Validation) {
var FormValidator = (function () {
function FormValidator(formid) {
this.emailPattern = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
this.formID = formid;
}
FormValidator.prototype.Validate = function () {
var errorsSum;
$('#' + this.formID).find('input[type="text"][validate], textarea[validate]').each(function (index, item) {
var validateType = $(item).attr('validate');
switch(validateType) {
case 'text':
case 'password': {
errorsSum += FormValidator.prototype.validateText(item);
break;
}
case 'email': {
errorsSum += FormValidator.prototype.validateEmail(item);
break;
}
}
});
return errorsSum == 0;
};
FormValidator.prototype.validateGeneric = function (element, validationFunc) {
var jqElement = $(element);
alert('tested element = ' + jqElement);
if(validationFunc(jqElement.val())) {
alert('tested element error = ' + jqElement.val());
element.removeClass('error');
return 0;
} else {
element.addClass('error');
}
alert('tested element success = ' + jqElement.val());
return 1;
};
FormValidator.prototype.validateEmail = function (element) {
return FormValidator.prototype.validateGeneric(element, function (elementValue) {
return FormValidator.prototype.emailPattern.test(elementValue);
});
};
FormValidator.prototype.validateText = function (element) {
return FormValidator.prototype.validateGeneric(element, function (elementValue) {
return elementValue != '';
});
};
return FormValidator;
})();
Validation.FormValidator = FormValidator;
})(Validation || (Validation = {}));
</script>
This is my form
#using (Html.BeginForm("Register", "Account", FormMethod.Post, new { #id = "register-form", #class = "form-horizontal"}))
{
...
#Html.TextBoxFor(m => m.Email, new { #placeholder = #L("Email"), #name = "email", #validate = "email" })
...
}
This is validation code
<script type="text/javascript">
$(function () {
$('#register-form').submit(function() {
return (new Validation.FormValidator('register-form').Validate());
});
});
</script>
I don't understand js so deep
You need to catch the submit event and prevent it from firing, validate the form, then submit if it was valid. Right now you are running the javascript as soon as it's submitted, but it just keeps submitting anyway since you don't stop the http request from being made.
On a related note, this is a huge mess. You don't need anything close to that much code just to validate emails and text presence on your form. This is all you need:
var validate = function(form){
var form_valid = true;
form.find('input[validate], textarea').each(function(index, el){
var type = el.attr('validate');
if (type == 'email') {
if (!el.match(/^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/)) { form_valid = false; el.addClass('error'); }
}
if (type == 'text') {
if (!el.val() == '') { form_valid = false; el.addClass('error'); }
}
});
return form_valid
}
$('#register-form').on('submit', function(){
validate($(this)) && $(this).submit()
});
Hope this helps...
Edit: made the example a bit more modular