Different unique token for the different instances of same page - javascript

I have a set of devices with device Id. On right clicking each device, it will pass device Id and open same page in multiple tabs(on each right click same page in new tab) with corresponding details of clicked device.
And here I have to keep a different token(random string variable) for each tab. And also token should not be changed on page refresh.
How can I do this ? I tried something but it's not working.
Created a random string, appended device Id to it and stored in local Storage as,
var prToken = window.localStorage.getItem('token');
if(prToken){
var subString = prToken.substring(10, prToken.length);
if(subString == GlobalVar.Inventory.device.id){
console.log(window.localStorage.getItem('token')+"====token");
}else{
var rString = GlobalVar.Inventory.randomString(10, '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',GlobalVar.Inventory.device.id);
window.localStorage.setItem('token', rString);
}
}else{
var rString = GlobalVar.Inventory.randomString(10, '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',GlobalVar.Inventory.device.id);
window.localStorage.setItem('token', rString);
}
here I am getting different token for each tab, but the problem is that, token is changing on page refresh.
Need help.

Solved myself, and it's working fine for me.
I
replaced 'token' variable with the device Id
. Then everything worked fine.
Then the code will be,
var prToken = window.localStorage.getItem(GlobalVar.Inventory.device.id);
if(prToken){
var subString = prToken.substring(10, prToken.length);
if(subString == GlobalVar.Inventory.device.id){
console.log(window.localStorage.getItem(GlobalVar.Inventory.device.id)+"====token");
}else{
var rString = GlobalVar.Inventory.randomString(10, '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',GlobalVar.Inventory.device.id);
window.localStorage.setItem(GlobalVar.Inventory.device.id, rString);
}
}else{
var rString = GlobalVar.Inventory.randomString(10, '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',GlobalVar.Inventory.device.id);
window.localStorage.setItem(GlobalVar.Inventory.device.id, rString);
}

Related

PHP not accessing Javascript cookie

I am creating a small CRUD web app where I need the user to enter their password when they wish to delete an item from the database, I have an onClick() on the delete button on the HTML table which passes the ID of the product to be deleted to the js function.
When the function runs I wish to confirm that they really want to delete the product and then ask for their password and store it in a cookie. BUT IT DOES NOT SEEM TO WORK :(
I am setting a cookie using javascript like
document.cookie = 'password=${userPassword},expires=${now.toGMTString()},path=/../includes/delete-product.inc.php;
With this line of code, when I console.log(document.cookie), it shows me the cookie in the console like
password=admin,expires=Sat, 12 Dec 2020 08:40:38 GMT,path=/../includes/delete-product.inc.php; PHPSESSID=3n1l3q6ksqitdpc76hjrero9ja
when I redirect to another PHP page using window.open() I can not access this cookie.
print_r($_COOKIE); <- only shows me the PHPSESSID only.
When I explicitly try to access the cookie using the following line
$userPassword = $_COOKIE[password]; it gives me undefined index 'password'
This is my code.
myproject/admin/view-products.php (This is the page where I try to set the cookie using javascript)
function deletePrompt(id) {
const now = new Date();
const time = now.getTime();
const expiresIn = time + (50 * 1000);
now.setTime(expiresIn);
const path = `../includes/delete-product.inc.php`;
const intent = confirm("Are you sure you want to delete this products");
if (intent === true) {
const userPassword = prompt("Enter password");
document.cookie = `password=${userPassword},expires=${now.toGMTString()},path=/../includes/delete-product.inc.php`;
console.log(document.cookie);
return;
window.open(`../includes/delete-product.inc.php?id=${id}`, "_self");
}
}
myproject/includes/delete-product.inc.php (This is the PHP page where I need to access the cookie)
<?php
require_once "./database-connection.inc.php";
require_once "./functions.inc.php";
if (isset($_SESSION["adminId"])) {
$productId = $_GET["id"];
$userPassword = $_COOKIE["password"]; //<- This throws undefined index error
if (deleteProduct($connection, $productId, $userPassword)) {
header("location: ../admin/view-products.php?msg=deleted");
exit();
}
else {
header("location: ../admin/view-products.php?msg=incorrectPass");
exit();
}
}
else {
header("location: ../admin/login.php");
exit();
}
To anyone else facing this the problem, the solution is that cookies don't get sent across directories, so you need to have the recipient file in the same domain if you wish to transfer cookies across them otherwise it won't work.
eg.
Following pattern will work
youProject/someDirectory/file1
youProject/someDirectory/file2
Following will NOT WORK
youProject/someDirectory/file1
youProject/someOtherDirectory/file2

Using browseForDoc() to define file path for saveAs() in javascript

I lurk this site all the time, but I think I have exhausted my options to find the info that I need.
I just want a button to trigger acrobat to run the browseForDoc() function, take the cPath the user selects and use that as the path for the saveAs() function. It seems like it should be easier than it has been. That is a folder-level script for adobe acrobat.
I get an error of "missing ; before statement 14". Besides that, it doesn't work. Please let me know what I am doing wrong.
//get windows user name
var getLoginName = app.trustedFunction(
function(){
//Get and return the user's login name
app.beginPriv();
return identity.loginName;
app.EndPriv();
}
);
var fileExt = ".pdf";
var filePath = function(cFS, cPath, bPromptToOverwrite){
this.cFS:cFS;
this.cPath=cPath;
this.bPromptToOverwrite=bPromptToOverwrite;
}
//Open save dialog,return user input values and saveas
var mySaveDialog = app.trustedFunction(
function browse(cPath,oDoc){
app.beginPriv();
app.browseForDoc(){bSave: true, cFilenameInit: oDoc, cFSInit: ""};
return this.cPath;
var myPath = new filePath{cPath: browse.cPath};
this.saveAs(myPath,myFile+fileExt);
app.endPriv();
}
);

Redirecting custom button URL based on User Role/User Public Group membership

I need to add some URL parameters in the Send Email button in Email related list in Case detail page.
I have added a custom detail page button with execute javascript. Below is the button code.
var loc;
var uRoleId = UserInfo.getUserRoleId();
if(
"{uRoleId}" == "General Permissions Team"){
loc = "/ui/core/email/author/EmailAuthor?p2_lkid=0031500001e729m&rtype=003&p3_lkid=5001500000TkUwp&retURL=%2F5001500000TkUwp&p26=xyz#gmail.com";
}
else{
loc = "/ui/core/email/author/EmailAuthor?p2_lkid=0031500001e729m&rtype=003&p3_lkid=5001500000TkUwp&retURL=%2F5001500000TkUwp&p26=test#gmail.com";
}
window.top.location.href = loc;
Now when I click on the button , I get a javascript error that user info is not defined.
Can you help me point out whats the issue with the button code.
UserInfo is not available in JavaScript. Instead you need to use {!$UserRole.Name} to get the role.
Try this:
var loc;
var uRoleName = "{!$UserRole.Name}";
if( uRoleName == "General Permissions Team"){
loc = "/ui/core/email/author/EmailAuthor?p2_lkid=0031500001e729m&rtype=003&p3_lkid=5001500000TkUwp&retURL=%2F5001500000TkUwp&p26=xyz#gmail.com";
}
else {
loc = "/ui/core/email/author/EmailAuthor?p2_lkid=0031500001e729m&rtype=003&p3_lkid=5001500000TkUwp&retURL=%2F5001500000TkUwp&p26=test#gmail.com";
}
window.top.location.href = loc;

How to download stock price data only when it is not erroneous (404)?

The script downloads historic stock prices from finance.yahoo.com. An array of tickers is used to loops through the script, creats liĀ“nks based on the ticker array and downloads the data associated to each ticker. However, some of the ticker symbols are not up to date anymore and as a result yahoo delivers a 404 page instead of a csv containing price information. The errorpage is then instead stored in a csv and saved to my computer. To not download these files I am looking for the string 'Sorry, the page you requested was not found.', which is contained within each of yahoos error sites as an indicator for a 404 page.
Behaviour of the code (output, see below code):
The code runs through all tickers and downloads all stock price .csv's. This works fine for all ticker, but some ticker symbols are not used anymore by yahoo. In the case of a ticker symbol that is not used anymore the program downloads a .csv containing yahoos 404 page. All files (also the good ones containing actual data) are downloaded in the directory c:\Users\W7ADM\stock-price-leecher\data2.
Problem:
I would like for the code to not download the 404 page into a csv file, but just do nothing in this case and move on to the next ticker symbol in the loop. I am trying to achive this with the if-condition that looks for the String "Sorry, the page you requested was not found." that is diplayed on yahoos 404-pages. In the end I hoope to download all csv's for tickers that actually exists and save them to my hdd.
var url_begin = 'http://real-chart.finance.yahoo.com/table.csv?s=';
var url_end = '&a=00&b=1&c=1950&d=11&e=31&f=2050&g=d&ignore=.csv';
var tickers = [];
var link_created = '';
var casper = require('casper').create({
pageSettings: {
webSecurityEnabled: false
}
});
casper.start('http://www.google.de', function() {
tickers = ['ADS.DE', '0AM.DE']; //ADS.DE is retrievable, 0AM.DE is not
//loop through all ticker symbols
for (var i in tickers){
//create a link with the current ticker
link_created=url_begin + tickers[i] + url_end;
//check to see, if the created link returns a 404 page
this.open(link_created);
var content = this.getHTML();
//If is is a 404 page, jump to the next iteration of the for loop
if (content.indexOf('Sorry, the page you requested was not found.')>-1){
console.log('No Page found.');
continue; //At this point I want to jump to the next iteration of the loop.
}
//Otherwise download file to local hdd
else {
console.log(link_created);
this.download(link_created, 'stock-price-leecher\\data2\\'+tickers[i]+'.csv');
}
}
});
casper.run(function() {
this.echo('Ende...').exit();
});
The Output:
C:\Users\Win7ADM>casperjs spl_old.js
ADS.DE,0AM.DE
http://real-chart.finance.yahoo.com/table.csv?s=ADS.DE&a=00&b=1&c=1950&d=11&e=31
&f=2050&g=d&ignore=.csv
http://real-chart.finance.yahoo.com/table.csv?s=0AM.DE&a=00&b=1&c=1950&d=11&e=31
&f=2050&g=d&ignore=.csv
Ende...
C:\Users\Win7ADM>
casper.open is asynchronous (non-blocking), but you use it in a blocking fashion. You should use casper.thenOpen which has a callback which is called when the page is loaded and you can do stuff with it.
casper.start("http://example.com");
tickers = ['ADS.DE', '0AM.DE']; //ADS.DE is still retrievable, 0AM.DE is not
tickers.forEach(function(ticker){
var link_created = url_begin + ticker + url_end;
casper.thenOpen(link_created, function(){
console.log("open", link_created);
var content = this.getHTML();
if (content.indexOf('Sorry, the page you requested was not found.') > -1) {
console.log('No Page found.');
} else {
console.log("downloading...");
this.download(link_created, 'test14_'+ticker+'.csv');
}
});
});
casper.run();
Instead of using the thenOpen callback, you can also register to the page.resource.received event and download it specifically by checking the status. But now you wouldn't have access to ticker so you either have to store it in a global variable or parse it from resource.url.
var i = 0;
casper.on("page.resource.received", function(resource){
if (resource.stage === "end" && resource.status === 200) {
this.download(resource.url, 'test14_'+(i++)+'.csv');
}
});
casper.start("http://example.com");
tickers = ['ADS.DE', '0AM.DE']; //ADS.DE is still retrievable, 0AM.DE is not
tickers.forEach(function(ticker){
var link_created = url_begin + ticker + url_end;
casper.thenOpen(link_created);
});
casper.run();
I don't think you should do this with open or thenOpen. It may work on PhantomJS, but probably not on SlimerJS.
I actually tried it and your page is strange in that the download doesn't succeed. You can load some dummy page like example.com, download the csv files yourself using __utils__.sendAJAX (it is only accessible from the page context) and write them using the fs module. You should only write it based in the specific 404 error page text that you identified:
casper.start("http://example.com");
casper.then(function(){
tickers = ['ADS.DE', '0AM.DE']; //ADS.DE is still retrievable, 0AM.DE is not
tickers.forEach(function(ticker){
var link_created = url_begin + ticker + url_end;
var content = casper.evaluate(function(url){
return __utils__.sendAJAX(url, "GET");
}, link_created);
console.log("len: ", content.length);
if (content.indexOf('Sorry, the page you requested was not found.') > -1) {
console.log('No Page found.');
} else {
console.log("writing...");
fs.write('test14_'+ticker+'.csv', content);
}
});
});
casper.run();

How to set your input fields with local storage variables using jquery

I am making a mobile web app using jquery mobile and jquery.
Now I have it so far that when I check my checkbox it saves my variables into the local storage from your browser. But it won't put these variables back into my input fields.
Here is my script. The function validate() saves the variables into local storage.
$(document).ready(function () {
if (localStorage["mail"]) {
$('#mail').val(localStorage["mail"]);
}else{
$('#mail').val("");
}
if (localStorage["password"]) {
$('#password').val(localStorage["password"]);
}else{
$('#password').val("");
}
});
function validate(){
if ($("remember:checked")) {
var mail= $("#mail").val();
var password= $("#password").val();
localStorage["mail"] = mail ;
localStorage["password"] = password;
localStorage.setItem("mail", mail) ;
localStorage.setItem("password", password) ;
}else{
alert("You didn't check it! Let me check it for you.")
}
}
Can anybody help me ?
thank you
it seems that $("remember:checked") is not a valid selector (a . or a # is missing). So probably your values are never saved into localstorage
when you check for existence of an element you should use length property instead
if ($("<your selector>").length) {
...
}
You are doing it wrong for setting and getting an item in local storage Use
localStorage.setItem('someval',1)
localStorage.getItem('someval'); // 1

Categories

Resources