JavaScript persist a search query through out the whole site - javascript

I'm currently fetching a query (e.g, http://localhost:49781/HTML/index.html?inputName=Marcus) from a html form using this following JavaScript:
function setSignedName() {
if (window.location.search.indexOf("=") >= 0) {
var split = window.location.search.split("=");
document.getElementById("signed_in_name").innerHTML += split[1];
} else {
document.getElementById("signed_in_name").innerHTML = "Not signed in";
}
running the script will get the result: Marcus.
I want this string to be persisted through out my site, so when the user navigates to another page the inputName will still be Marcus.
What is the best way of achieving this?
Edit: This approach is only for display/non-production use, I know using a server side language like PHP is the best approach.

I believe the best way is using localStorage. It works in all major browsers and it's easy to use:
function setSignedName() {
var userName = "";
if (window.location.search.indexOf("=") >= 0) {
var split = window.location.search.split("=");
userName += split[1];
} else {
userName = "Not signed in";
}
document.getElementById("signed_in_name").innerHTML = userName;
localStorage.setItem("userName", userName);
}
To access it:
var userName = localStorage.getItem("userName");
And this is it. Check for it in the Resources tab in Developer tools(F12) in your fav broswer.

You'll want to either repopulate it through GET parameters in your server side language, or if you want to hack it together, use a cookie and repopulate it with JavaScript on page load with "pushState".
https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history#The_pushState()_method

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 do I encrypt a variable in javascript?

I have been searching for ages and couldn't find a way to encrypt my javascript variable, because its used for a password:
function lg() {
var input = document.getElementById("values").value;
if (input == pass) {
$("nil").replaceWith($("<success>" + "Success!" + "</success>"));
sleep(4000);
sleep(2000);
window.location.replace("http://google.com");
}
else if (input == "") {
$("nil").replaceWith($("<error>" + "Error: No input detected!" + "</error>"));
}
else {
$("nil").replaceWith($("<error>" + "Incorrect Password!" + "</error>"));
}
}
var pass="test3r"; // The one I need to encrypt
I don't think you would need my html or css as its just my javascript variable I need to encrypt. The variable I need to encrypt is my var pass one.
If your javascript is running on client side so it's not best decision to hold password in js code. And any user can just skip password check by editing code.
But if you really need this, only option I see is to use hash of password and some js library to create exact hash of user input.
For example if you will you md5 hash function (not really strong one, but there are lost of implementations in js) your password hash will look like a50bdfb74649a14c1f86b6d012f2caad
And password check will looks like if (md5(input) == pass) { ...
}
You should read about hash functions and use "salt" when hashing password to make decoding your password harder.

Lotus notes automation from browser

I have been trying to automate Lotus Notes mail fillup from a browser interface.
After refering to Richard Schwartz's answer, i came up with this piece of code using the Lotus.NotesSession class.
function SendScriptMail() {
var mToMail = document.getElementById('txtMailId').value
var mSub = document.getElementById('txtSubject').value
var mMsg = document.getElementById('txtContent').value
var Password = "yyy"
alert("1");
var MailFileServer = "xxx.com"
var MailFile = "C:\Program Files\IBM\Lotus\Notes\mail\user.nsf"
alert("2")
var Session;
var Maildb;
var UI;
var NewMail;
var From = "user#xxx.com"
try {
alert("3")
// Create the Activex object for NotesSession
Session = new ActiveXObject("Lotus.NotesSession");
alert("4")
if (Session == null) {
throw ("NoSession");
} else {
Session.Initialize(Password);
// Get mail database
Maildb = Session.GetDatabase(MailFileServer, MailFile);
alert("5")
if (Maildb == null) {
throw ("NoMaildb");
} else {
NewMail = MailDB.CreateDocument();
if (MailDoc == null) {
throw ('NoMailDoc');
} else {
// Populate the fields
NewMail.AppendItemValue("Form", "Memo")
NewMail.AppendItemValue("SendTo", mToMail)
NewMail.AppendItemValue("From", From)
NewMail.AppendItemValue("Subject", mSub)
NewMail.AppendItemValue("Body", mMsg)
NewMail.Save(True, False)
NewMail.Send(False)
}
}
}
} catch (err) {
// feel free to improve error handling...
alert('Error while sending mail');
}
}
But now, alerts 1,2,3 are being trigerrd, and then the counter moves to the catch block. The lotus notes session is not being started.
In a powershell script that I was previously looking at there was a code regsvr32 "$NotesInstallDir\nlsxbe.dll" /s that was used before the Session = new ActiveXObject("Lotus.NotesSession");. Is there something similar in javascript too, if so how do i invoke that dll.
I think I've realised where I am going wrong. According to me, upto alert("5") things are good. But since Lotus.NotesSession doesn't have a CreateDocument() method, it is throwing the error. I am not sure how to create the document and populate the values though.
Since you've chosen to use the Notes.NotesUIWorkspace class, you are working with the Notes client front-end. It's running, and your users see what's happening on the screen. Are you aware that there's a set of back-end classes (rooted in Lotus.NotesSession) instead of Notes.NotesSession and Notes.NotesUIWorkspace) that work directly with Notes database data, without causing the Notes client to grab focus and display everything that you're doing?
Working with the front-end means that in some cases (depending on the version of Notes that you are working with) you're not going to be working directly with the field names that are standard in Notes messages as stored and as seen in the back-end. You're going to be working with names used as temporary inputs in the form that is used to view and edit the message. You can see these names by using Domino Designer to view the Memo form.
Instead of using 'SendTo', try using:
MailDoc.Fieldsettext('EnterSendTo', mToMail)
Regarding the Body field, there's no temporary field involved, however you haven't really explained the difficulty you are having. Do you not know how to display the interface that you want in the browser? Do you not know how to combine different inputs into a single FieldSetText call? Or are you just dissatisfied with the fact that FieldSetText can't do any fancy formatting? In the latter case, to get more formatting capability you may want to switch to using the back-end classes, which give you access to the NotesRichTextItem class, which has more formatting capabilities.

accessing a node moudule from javascript file using jquery

i am building a web site using nodejs/javascipt/jquery/html/css and mysql.
lets say i have an html login page that has receives an input from the user (name && psw)
and i have a file:
login.js:
var node = reuqire('some module');
$(document).ready(function() {
var username = $('#name');
var password = $('#password');
$('#login_button').click(function(){ login(username.val(),password.val())});
});
without the require it works fine.(i also tried to move the require into the ready function)
for some reason it does not let me use another module.
any help?
thank you :)
Calling server-side functions in a client-side file like that is not possible. However, looking at your comment I suggest the NowJS library.
NowJS does not allow you to mix client-side/server-side JavaScript in one file (because that just does not make sense, and if it did it would be a high security risk). But it does allow you to define a function server-side (which will e.g. check credentials), which you can call client-side with no additional hassle. When that server-side function is done you can send a client-side function with the result (i.e. correct/wrong credentials). That way you can achieve what you want rather easily.
If you've read the basic tutorials, you could implement it like this (partly pseudocode since I don't know how you're checking login details etc.):
At the server-side:
everyone.now.checkLogin = function(username, password, callback) {
db.query("...", function(results) {
if(results.correct) {
callback(true);
} else {
callback(false);
}
});
};
At the client-side:
$("#login_button").click(function() {
var username = $("#username").val(),
password = $("#password").val();
now.checkLogin(username, password, function(correct) {
if(correct) {
$("#correct_message").show();
} else {
$("#wrong_message").show();
}
});
});

Categories