Reading Session Value in Javascript - javascript

I read a bunch of links and answers and nothing worked. So in controller I have this:
Session["MySession"] = "HelloMaybe";
and in the page I have this:
window.onbeforeunload = function () {
console.log("Before Unload Window");
var somethingElse = '#Session["MySession"]';
console.log(somethingElse);
};
I see that script is running because it prints my first log message but there is nothing in there for value of session.
How can I do this?

var somethingElse='#System.Web.HttpContext.Current.Session["MySession"].ToString()'

Related

Only run a function once in JavaScript? [duplicate]

I'm using a page loader on the front page of my website, I'd like it to run only the first time someone visits my website, so later on since the page will be cached it'll execture faster and thus I won't need the loader the next times he visits.
I thought using storing a signal to caches/cookies to do so, but I have no idea how ?
here is the loader javascript :
function myFunction() {
var myVar = setTimeout(showPage, 1000);
}
function showPage() {
$("#loader_sec").css("display","none");
$("#bodyloader").css("display","block");
}
myFunction();
<div id="loader_sec">
...
</div>
How should I configure caches/cookies to launch this code only the first time someone visits ? If there are better ways to do so please suggest.
Try this:
function myFunction() {
var myVar = setTimeout(showPage, 1000);
}
function showPage() {
$("#loader_sec").css("display","none");
$("#bodyloader").css("display","block");
}
if(!localStorage.getItem("visited")){
myFunction();
localStorage.setItem("visited",true);
}
<div id="loader_sec">
...
</div>
Try with Session/local storage. Like this -
$(window).load(function () {
$(function () {
if (!sessionStorage.getItem("runOnce")) {
// Your code goes here....
sessionStorage.setItem("runOnce", true);
}
});
});
You'll need to persist some data on the user's device in order to know that they have visited your site before. You would do this via local storage or cookies.
Here is a simple library you can use to read/write cookies: https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie/Simple_document.cookie_framework
You could write a value to a cookie when the user has been shown the page loader. A check for this value when the page loads will let you know if the loader has been displayed previously or not and inform your decision about whether it should be displayed this time.
I would do the logic in a caching/data access layer. You can use https://github.com/kriskowal/q for executing functions as a callback when another function completes.
Then you can do
getData(key)
.then(function () {
hideLoader(); // Function for your show/hide logic
});
or something of the sort.
getData would look something like:
var getData = function (key) {
var deferred = Q.defer();
if (cache[key]) {
deferred.resolve(cache[key]);
} else {
//Data request logic that returns 'data'
deferred.resolve(data);
}
return deferred.promise;
};
This way you're not guessing how long your requests are going to take and you're not forcing a second long load time on your user because the page will load as soon as your data has been retrieved.
By the way, the cache here is just a key/value store. Aka var cache = {};

When does window.location.href get updated?

I have a scenario where I wanted to check if the browser can go back to previous page via history.back(). For this purpose, I followed this answer https://stackoverflow.com/a/24056766/2948305, the code for which I am pasting below
function historyBackWFallback(fallbackUrl) {
fallbackUrl = fallbackUrl || '/';
var prevPage = window.location.href;
window.history.go(-1);
setTimeout(function(){
if (window.location.href == prevPage) {
window.location.href = fallbackUrl;
}
}, 500);
}
When window.history.go(-1) is executed, what will window.location.href resolve to ? Will it resolve current page or the previous page(history -1) .
console.log(window.location.href);
prints the current page URL. Does this mean, until the previous page is completely loaded, window.location.href will resolve to the current page.
Or until this function is fully executed(with/without the setTimeout), it will always point to current page URL.
To be specific, when exactly will window.location.href get updated?
When a user changes location of the tab, a new window will be created for that session.
That code doesn't even get executed because window changes completely and that is also being lost.
I believe this code can prove what I said.
```
const foo = 'foo';
const oldWindow = window;
window.history.go(-1);
window = oldWindow;
foo // ReferenceError
```
window doesn't point to previous window. Using setTimeout doesn't change the result.
Also tried this but seems like no change
`
const foo = 'foo';
const oldWin = Object.create(window);
window.history.go(-1)
setTimeout(() => {
window = oldWin;
}, 500)
`

What are the attributes of a new window, if opened by a window.open function?

If I add this code between a <script> and a </script>:
function test()
{
var newWindow = window.open("https://stackoverflow.com/", "a", "width = 600,height = 400");
document.write(newWindow.location.href);
document.write(newWindow.innerWidth);
}
test();
And the output is "about:blank" and 0, though I think it should be "https://stackoverflow.com/" and 600.
I am so confused about this and waiting for a explanation.
AND: if I do want to get the URL of the new window, how should I do?
MANY THANKS.
You can capture these values asynchronously if you wait on the load event:
var newWindow = window.open('http://www.stackoverflow.com', 'a', 'width=600,height=400')
newWindow.addEventListener('load', function () {
console.log(newWindow.location.href);
console.log(newWindow.innerWidth);
});
However, as James Thorpe points out, this will only work if the new window is in the same domain as the page where the script is running, and this happens asynchronously, so whatever you're trying to accomplish by using document.write() might not work.

Init localStorage after every refresh

I would like to initialize localStorage object every time a user does a refresh by F-5.
Can i do such a thing?
The localStorage object is working fine by setItem and getItem methods.
However, I would like to know if i have the option to init this object every refresh action.
For example:
I have two different pages in my app. A.js and B.js.
When loading B.js i set the localStorage:
var id = getId();
window.localStorage.setItem("Id", id );
After that when i clicking on a button for going to A.js i am doing:
var selectedId = window.localStorage.getItem("Id");
if (selectedId !== null){
var intSelectedId = parseInt(selectedId );
//DO LOGIC
}
I would like to delete ("Id", id) key-value pair every refresh.
How can i do it?
Maybe like this ?
//declare in global scope
var myinitvalue = "blah";
//handle what happens just before page unloads
window.onbeforeunload = function() {
window.localStorage.setItem("Id", myinitvalue);
}
Unfortunately the side effect of this is that the value will also reset if browser tab is closed or if back button is clicked.
If you want to delete item with key Id once your page is loaded, do
window.onload=function(){
localStorage.removeItem("Id");
}

How to call a site's function from a Chrome extension?

I'm trying to make a Chrome extention for myself, so that when I visit any sort of channel at Twitch.tv, the chat will automatically hide.
I've been looking at it with Firebug and I found toggle_chat(). If I type that in the console, the chat is no longer visible.
In my userscript file, I have written
window.onload = function() {
toggle_chat();
}
but it says
Uncaught ReferenceError: toggle_chat is not defined" in the console when I load a Twitch channel.
Any ideas how to make this work?
This has nothing to do with timing. Chrome extensions and content scripts execute in an isolated world, meaning they have no access to the page's javascript including functions. You could make it so that your content script appends a <script> element that then calls the page function that you want but it would be far easier to just simulate a click on the #right_close element. You can do this with pure Javascript like this:
window.onload = function(){
var evObj = document.createEvent('Events');
evObj.initEvent('click', true, false);
document.querySelector('#right_close').dispatchEvent(evObj);
}
I know this is very hacky, but it gets the job done, and sometimes that exactly what you need. :) It'll check for the function roughly ever half second until it exists. When it's finally there, it'll call the function then clear the timer.
window.onload = function() {
var id = null;
var check = function() {
if (typeof toggle_chat === "function") {
toggle_chat();
clearInterval(id);
}
}
id = setInterval(check, 500);
}

Categories

Resources