How to update value instead of restarting the app - javascript

I have this piece of code in my iOS app inside WebViewController.swift:
var pushIDOneSignal = userID
if pushIDOneSignal == nil
{
// do nothing
}
else
{
webviewurl += pushIDOneSignal! //Add PushID token to the URL
}
I'm using pushIDOneSignal to get the playerid for the user. The problem is when the user opens the app the first time, we get a nil value; because has to accept permission notifications first.
Somehow I managed to create a way to get the playerid, but it only works if the user accepts the notifications and then, closes the app, and opens again.
How can I make the app try to read this again: if pushIDOneSignal == nil after the user has accepted notifications? Then that time, will get the else condition and then we will get the playerid.
Edit:
I have idea-
if pushIDOneSignal == nil
{
// do nothing
}
else
{
webviewurl += pushIDOneSignal! //Add PushID token to the URL
}
How i can make keeps looping when value is nil? Thanks.

Related

Allow a user access to 2 specific pages using jQuery

I have a site where users must log in to access pages. When they are not logged in I redirect them to the log in page and it then sets a cookie / token. I know this is not the most stable way of doing it but it works and its not a high traffic site whatsoever. maybe 5 users. My issue now is I need to give the users access to a contact us page even if the cookie / token is not set / valid. I tried to add another conditional to the function but it creates an infinite loop. Any ideas of handling this situation?
jQuery :
function checkIfTokenExists() {
var current_url = window.location.pathname;
var logInToken = _siteNs.Utils.readCookie('SST');
if (!logInToken) {
if (current_url != '/login.html') {
window.location.replace('/login.html');
}
} else if (logInToken) {
_siteNs.authenticateUtils.authenticateSite();
}
}
What I would like is if url is equal to /contact.html the users will be able to access regardless of cookie / token
You can early return before the token check, if the current URL is the contact page.
function checkIfTokenExists() {
var current_url = window.location.pathname;
var logInToken = _siteNs.Utils.readCookie('SST');
if (current_url == '/contact.html') {
return;
}
// ... rest of your code

How can I display a Javascript prompt once on website load?

I have a javascript prompt that executes when I open my website for the first time. The basic function of this prompt is to ask the user for their name, and then insert it into a header I.E. "Hello, 'user'!" I have multiple pages on my website, and whenever I navigate to a different page and then navigate back to the home page, the prompt is displayed again, asking the user the same question over and over. Is there any way to have the prompt display only once on the first load of the website, and then keep the user's name in a variable until they close the website?
Here is my javascript:
function askName() {
let username = prompt("To make your time on this website better, please enter your name.");
if (username != null) {
document.getElementById("userpara").innerHTML = "Hello, " + username;
} else {
document.getElementById("noUser").innerHTML = "Welcome, Stranger!";
}
}
And here is my Html:
<h1 id="userpara" style="text-align: center;"></h1>
<h1 id="noUser" style="text-align: center;"></h1>
To execute the function on page load, I used the onload function in the body tag in html like this:
<body onload="askname()">
...
</body>
Feel free to correct me on any of my code as well, since I'm still learning :)
Try using sessionStorage:
function askName() {
let username = sessionStorage.getItem('username');
if (username === null) {
username = prompt("To make your time on this website better, please enter your name.");
}
if (username != null) {
document.getElementById("userpara").innerHTML = "Hello, " + username;
sessionStorage.setItem('username', username);
} else {
document.getElementById("noUser").innerHTML = "Welcome, Stranger!";
}
}
sessionStorage is different from localStorage in that sessionStorage is wiped whenever you close the window/tab, which is what you want. localStorage stays until a user clears the cache or you remove the data through script.
There are a variety of ways to persistently store information on a client's web browser:
Cookies
Sends the information to the web server.
Used for a tiny amount of data
Can be inconvenient to work with, usually requires some parsing.
Data can persist upon closing the web browser, or it can be automatically deleted when it closes, by using a session cookie.
localStorage/sessionStorage
Information stays on the client, doesn't automatically get sent to the web server
Easy to work with
Generally used with a small amount of data
sessionStorage data gets deleted upon closing the browser, while localStorage data persists
a new instance of sessionStorage data is created when a new tab or window is opened, so other tabs/windows can't access the same sessionStorage data
IndexedDB
Information stays on the client, doesn't automatically get sent to the web server
Allows storing large amounts of data
Works asynchronously
Complicated to use
Data persists upon closing the browser
Probably the easiest way to do this is by using localStorage:
function askName() {
let username = localStorage.getItem('username');
if (!username) {
username = prompt("To make your time on this website better, please enter your name.");
}
if (username != null) {
document.getElementById("userpara").innerHTML = "Hello, " + username;
localStorage.setItem('username', username);
} else {
document.getElementById("noUser").innerHTML = "Welcome, Stranger!";
}
}
Note that the information doesn't get cleared upon closing the browser (probably the closest thing to do that is a session cookie, but it comes with the concerns of using cookies). Alternatively you can just use sessionStorage, if you don't need other tabs/windows accessing the same data.
save the value to localStorage and check next time if value there in localStorage
function askName() {
var user=localStorage.getItem('Username');
if(user){
document.getElementById("userpara").innerHTML = "Hello, " + user;
}
else{
let username = prompt("To make your time on this website better, please enter your name."); if (username != null) {
user=localStorage.setItem('Username', username)
document.getElementById("userpara").innerHTML = "Hello, " + username;
} else {
document.getElementById("noUser").innerHTML = "Welcome, Stranger!";
}} }

how to force redirect to login page in javascript

I am building a website where I want users to have to log in to be able to view a certin page (kn this case it is called gallery.php) I implemented some code I found on this site, which redirects the user back to the login page when they click on the gallery link in the menu. However when I log in, and get redirected to the gallery again, the website does not acknowledge that I have logged in and redirects me back to the login page again. I am aware that questions like this have been asked before, but any help would be appreciated. My code is bellow
//from login.html
<!--//
/*This Script allows people to enter by using a form that asks for a
UserID and Password*/
function pasuser(form) {
if (form.id.value=="Admin") {
if (form.pass.value=="rycbar123") {
var sessionTimeout = 1; //hours
var loginDuration = new Date();
loginDuration.setTime(loginDuration.getTime()+(sessionTimeout*60*60*1000));
document.cookie = "SistaDansenSession=Valid; "+loginDuration.toGMTString()+"; path=gallery.php";
location="gallery.php"
} else {
alert("Invalid Password")
}
} else { alert("Invalid UserID")
}
}
//from gallery.php
<!--force login code-->
<script type="text/javascript">
if (document.cookie.indexOf("SistaDansenSession=Valid") == -1) {
alert("You must be logged in to view this page")
location.href = "login.html";
}
else {
alert("login succesful")
} </script>
Thanks so much
Try changing:
if (document.cookie.indexOf("SistaDansenSession=Valid") == -1)
to
if (document.cookie.indexOf("SistaDansenSession") < 0)
When you set the cookie, you are setting the cookie attribute 'SistaDansenSession' equal to the value 'Valid'. In your original code, you are attempting to retrieve a cookie attribute 'SistaDansenSession=Valid', whereas the attribute you want to retrieve is just 'SistaDansenSession'. When the cookie is set, the attribute exists, so it will have an index that is >= 0. In that case, the redirect to the login does not occur - which I think is your desired behavior.

On page unload strophe.js sends request twice! why?

I'm new to Xmpp server and strophe.js, I implement it into my website for messaging. There is a problem when I am send a message it works fine, but after sending a message if I reload the page immediately then I saw that that message, which I send before reload saved in Xmpp server twice, and when I retrieve message from server obviously it return duplicate message. It is so embarrassing.
Can any one tell me any solutions to stop twice requesting when page load?
I saw a post where one developer told that he face with same problem and contact to strophe team they suggest him to replace the line 2566 of strophe.js file with this code
if (req.sends == 0) {
sendFunc();
}
I have already done it but my problem is still there. :(
Thanks,
biswajitGhosh
You need to create multiple divs/windows, one for each chat. Strophe is meant to be asynchronous so you don't have to reload. Reloading defeats the purpose of strophe. Add a handler to your connection once you attach/connect.
connection.addHandler(onMsg, null, 'message');
In your message handler, you can then determine which conversation the message belongs to and append it to the appropriate div.
var onMsg = function (msg) {
var elems = msg.getElementsByTagName('body');
if (elems.length > 0) {
var type = msg.getAttribute('type');
var from = msg.getAttribute('from');
if (type == "chat") {
//new chat message
}
}
return true;
}

Phonegap db.transaction callback firing more than once

I am having an issue with a project I am working on using phonegap
[Step 1] -
I am storing a users login "session" locally (Web SQL) from a web server. This is working fine, I can successfully connect to the web server, post the user login data, get a response from the server, create the local User database and store the user "session" value
[Step 2] - I then need to pass this "session" value back to the web server, and receive response data from the server. Again, this works as expected but the problem is, the callback function is being executed twice.
Step 2 is called when the user taps a button on the screen, and it doesn't seem like the reason that Step 2 is being called twice if because phonegap is picking up the tap more than once, I have tried:
$(".yes_sync").live("tap", function(){
console.log("tap!");
...
Which only logs a single tap event.
When the user taps I am calling:
var db = window.openDatabase("MVIdb", "1.0", "MVIsqlite", 200000);
db.transaction(getUserId, getUserIdFailed, getUserIdsSuccess);
The getUserId, getUserIdFailed and getUserIdsSuccess functions look like so:
function getUserId(tx){
tx.executeSql("SELECT * FROM user WHERE id = '1'", [], getUserIdsSuccess, getUserIdFailed);
}
function getUserIdFailed(tx, results){
console.log("Error retrieving user session ID");
}
function getUserIdsSuccess(tx, results){
console.log("Success retrieving user session ID");
if(typeof results != 'undefined'){
var return_value = results.rows.item(0).user_id;
user_session_id = return_value;
var token = $.md5(user_session_id+"whatever!");
$.get('http://localhost/project/dummyserver/sync?user_id=' + user_session_id + '&token=' + token, function(data) {
data = $.parseJSON(data);
for (var key in data){
console.log(data[key]['user_id']);
}
$(".ui-loader").fadeOut();
jQuery.mobile.changePage("_sync_complete.html", { role: "dialog", transition: "pop" } );
});
}
}
As you can see, the last line in the callback for the $.get in the callback for the success opens a pop up dialogue. This dialogue is being called twice.
I have noticed that phonegap has a lot of asynchronous behaviour, which I understand is to prevent the system from feeling "laggy", but surely it shouldn't be executing a callback function on a db.transaction more than once?
Your callback is called twice because you are passing it both to the executeSql command and the transaction. Remove it from one to make it work as expected.
Not the most elegant solution, but I went with using a global variable
var has_getUserIdsSuccess = false;
And in the callback function:
if(typeof results != 'undefined'){
if (has_getUserIdsSuccess == false){
has_getUserIdsSuccess = true;
// as per above
has_getUserIdsSuccess = false; // set it back to false so use can press the execute this function again later
}
I am still interested to see if anyone has a better solution!

Categories