load an ad (div) just once on first load - javascript

I wanted to know how can I have a div that has an ad to load or become visible ONLY the first time you load the page but hide it every time the page is refreshed?
I only have the code to load the div with Jquery but don't know how to hide it after refreshing the page:
$(document).ready(function() {
$(".referralProgram").fadeIn("slow");
});

Use a cookie:
$(document).ready(function() {
if (!readCookie("adSeen")) {
$(".referralProgram").fadeIn("slow");
createCookie("adSeen", "1", 1000);
}
});
function createCookie(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
} else var expires = "";
document.cookie = name + "=" + value + expires + "; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
Cookie functions from quirksmode.org.
Edit: Since so many are discussing how to deal with this if cookies are disabled, it should be pointed out that server session implementations rely on either a cookie, or a session identifier in the url. At best, you could only prevent displaying the ad for the same user as long as the session identifier is in the url. Returning to the home page sans session id would re-display the ad. Additionally, a careless implementation (and even some careful implementations) could result in false positives for other users if a user shares a url. localStorage solutions won't work with cookies disabled in most, if not all, browsers.

You'll need a way to keep track of when an ad has been displayed to the user. Set a cookie when the ad is created and check for it before displaying again?

You can use client side persistent storage to flag the user has already seen this. Here are 3 options:
1) Cookies - Set a cookie on the visiting users machine.
2) HTML5 Storage - You can store the flag in browser (HTML5 Only) storage.
3) Server Session - If you are using middleware (PHP, ASP.NET, Java, etc.) you can track via a session variable (this is an abstraction of a cookie and is only as persistent as you create it to be).

I am not sure what your server side implementation is like, but if you are worried about cookies being turned off you could handle this on the server side using session state.

Related

How to save a javascript variable

I have a javascript variable, which is incremented by a javascript function in a .php script, only problem is that the page reloads when the function is called, so I need some way of saving the variable to be the same when the page is either reloaded or whenever you enter it.
I know you can do a local save but I am not quiet sure if it saves the variable when you leave the website.
My variable is in a html script.
<script type="text/javascript">
var varNumber= 1;
document.getElementById("varNumber").innerHTML = varNumber;
document.getElementByID("varNumber").value = varNumber;
function addToVariable() {
varNumber= varNumber+ 1 ;
document.getElementById("varNumber").innerHTML = varNumber;
}
</script>
Here are three client-side methods to save JavaScript variables across page refreshes and descriptions on how long they can persist data.
Saving a JavaScript variable with local storage
Saving a JS variable using local storage is easy and convenient with modern browsers.
var get = function (key) {
return window.localStorage ? window.localStorage[key] : null;
}
var put = function (key, value) {
if (window.localStorage) {
window.localStorage[key] = value;
}
}
To save and read an object instead of a simple variable:
localStorage.yourObject = JSON.stringify(obj);
obj = JSON.parse(localStorage.yourObject || "{}");
Persistence:
User agents may, if so configured by the user, automatically delete
stored data after a period of time.
For example, a user agent could be configured to treat third-party
local storage areas as session-only storage, deleting the data once
the user had closed all the browsing contexts that could access it.
This can restrict the ability of a site to track a user, as the site
would then only be able to track the user across multiple sessions
when he authenticates with the site itself (e.g. by making a purchase
or logging in to a service).
However, this also reduces the usefulness of the API as a long-term
storage mechanism. It can also put the user's data at risk, if the
user does not fully understand the implications of data expiration.
References:
http://dev.w3.org/html5/webstorage/
Persisting values in JavaScript object across browser refresh
How persistent is localStorage?
Saving a JavaScript variable with cookies
Saving a variable with cookies:
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
Persistence:
Session cookies - these are temporary and are erased when you close
your browser at the end of your session.
Persistent cookies - these remain on the client hard drive until they
are erased or expire.
This is ultimately user-dependent. They could be paranoid about
cookies and local storage, and set them to session-only or none at
all.
REF: Set cookie and get cookie with JavaScript
Saving a JavaScript variable with window.name
You could also use the window’s name window.name to store the information using a JavaScript session.
Persistence:
This only works as long as the same window/tab is used.
REF: http://www.thomasfrank.se/sessionvars.html
You can use localStorage on client side
<script>
localStorage.setItem("mykey",99); // set a variable
var varNumber = localStorage.getItem("mykey"); // retrieve variable
</script>
You could use AJAX to execute PHP, like:
<?php
session_start(); $r = array();
if(isset($_POST['holdNumber'])){ // assumes {holdNumber:numberHere} sent through AJAX
if(preg_match('/^\d+$/', $_POST['holdNumber']){
$r['heldNumber'] = $_SESSION['holdNumber'] = $_POST['holdNumber'];
}
else{
// holdNumber hack
}
}
elseif(isset($_POST['load'])){
if(+$_POST['load'] === 1){ // assumes sending {load:1} in AJAX
if(isset($_SESSION['holdNumber']){
$r['heldNumber'] = $_SESSION['holdNumber'];
}
else{
$r['heldNumber'] = $_SESSION['holdNumber'] = 0;
}
}
else{
// load hack
}
}
echo json_encode($r);
?>

How to delete the javascript cookies when the session invalidates on its own?

I have declared a cookie in my code which is created after specific function gets successful. I manipulate the cookie based on the method success or failure. Below is the code that I have used to create the cookie,
setCounterOfSuccess : function (c_name,value,days){
var expires='';
if (days){
var date=new Date();
date.setTime( date.getTime() + (days*24*60*60*1000) );
expires='; expires=' + date.toGMTString();
}
document.cookie= c_name + '=' + value + expires + '; path=/';
},
getCounterOfSuccess : function(c_name){
var nameEQ = c_name + '=';
var ca=document.cookie.split(';');
for (var i=0; i<ca.length; i++) {
var c=ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ)===0)
return c.substring(nameEQ.length,c.length);
}
return null;
},
deleteCounterOfSuccess : function (name){
this.setCounterOfSuccess (name,'',-1);
},
I want these to be session cookies. So while setting the value I am setting them as below, I am passing ‘ ’ as last parameter to set them as session cookies.
I assume they will expire when the browser will be closed.
this.setCounterOfSuccess ("counterOfSuccess", Counter, '');
I am also deleting the cookie when I hit the logout button from the website. It looks like below,
logout: function()
{
this.deleteCounterOfSuccess ("counterOfSuccess");
}
So I am handling 2 ways of my how my cookies should get deleted. Now the problem is when I leave my website logged in for some time, it automatically logs out after a certain time period as expected. Which means that the session gets terminated or invalidated on its own. Now in this case if the browser is not closed and if I login again, the cookie is still there. And I don’t want that to happen. I want to have new cookie created at every session so that I can track the session related activities in the same.
Can anyone please advise how can I achieve this? How can I delete this cookie when the session terminates on its own after leaving it alone for a long time?
Thanks a lot.

javascript - read a seperate tab to check if it's open

I'm looking for a way to somehow read / check if another browser tab is open before opening the requested tab.
For example:
This is for my traffic exchange site, they just open mysite.com/surf.php and leave it viewing user's submitted sites in a frame. They earn points just for leaving that running.
Now lets say USER A has SURF PAGE A running fine and then opens SURF PAGE B then he has 2 mysite.com/surf.php running and earning double the points everybody else will earn.
What I want to happen is:
USER A has SURF PAGE A running fine and then tries to open SURF PAGE B which will check if another mysite.com/surf.php is already open and if it is to redirect the request for the 2nd surf page to another mysite.com/surf-error.php
So they can only ever have 1 mysite.com/surf.php running at any given time.
How would I go about doing this?
Browser windows on the same domain in the same browser can exchange some information via:
Cookies
Local Storage
Communication with a common server
You can use 1) or 2) to store some information about an active page and refuse to let other pages be active if one is already active.
But, the most reliable way to enforce policies like you are asking about is to use the actual server to enforce it. If users have a login, then code the server to only allow a logged in user to accumulate points for one site at a time.
Other than these options, if you want to enforce it all client-side, you would probably need a browser-plugin that could monitor all open browser windows (which I assume is not practical). You cannot do monitoring of multiple windows opened by the user from plain javascript in a web page.
when you start tracking time for someone set a session variable
session.trackingtime = true
when you check again to start tracking time make sure that value is set to false. When you stop tracking time set the variables to false.
I have done something very similar today. Just update the else if part to do a redirect in your case.
// helper function to set cookies
function setCookie(cname, cvalue, seconds) {
var d = new Date();
d.setTime(d.getTime() + (seconds * 1000));
var expires = "expires="+ d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
// helper function to get a cookie
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
// Do not allow multiple call center tabs
if (~window.location.hash.indexOf('#admin/callcenter')) {
$(window).on('beforeunload onbeforeunload', function(){
document.cookie = 'ic_window_id=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
});
function validateCallCenterTab() {
var win_id_cookie_duration = 10; // in seconds
if (!window.name) {
window.name = Math.random().toString();
}
if (!getCookie('ic_window_id') || window.name === getCookie('ic_window_id')) {
// This means they are using just one tab. Set/clobber the cookie to prolong the tab's validity.
setCookie('ic_window_id', window.name, win_id_cookie_duration);
} else if (getCookie('ic_window_id') !== window.name) {
// this means another browser tab is open, alert them to close the tabs until there is only one remaining
var message = 'You cannot have this website open in multiple tabs. ' +
'Please close them until there is only one remaining. Thanks!';
$('html').html(message);
clearInterval(callCenterInterval);
throw 'Multiple call center tabs error. Program terminating.';
}
}
callCenterInterval = setInterval(validateCallCenterTab, 3000);
}

Stop people having my website loaded on multiple tabs

I want users to browse my site from only one tab in their browser. How can this be done? Would I use javascript and cookies?
For example, I have a website: www.example.com - and I want my clients to only be able to visit the site from one single tab in one browser. If they open another tab and load the site (or a subpage of the site) - I want an alert "Can't open multiple instances", and then redirect them to an error page.
Once thing to note - if the user changes the address from www.example.com/action/door/mine.aspx to www.example.com - that should work fine, because the user is in the same (original) tab.
Any help will be appreciated. Thanks in advance.
I've created a simple solution for this. The master page layout creates a tab GUID and stores it in sessionStorage area of the tab. The using an event listener on the storage area I write the tab GUID to the sites localStorage area. The listener then compares the tabs GUID to the one written to site storage and if they differ then it knows more than one tab is open.
So if I have three tabs A,B,C then click something in tab C, tab A and B detect another tab is open and warn user of this. I haven't yet got to fixing it so the last tab used get's notification, work in progress.
Here's the JS I have in master page, plus in the login page I have a localStorage.Clear to clear last tab from previous session.
// multi tab detection
function register_tab_GUID() {
// detect local storage available
if (typeof (Storage) !== "undefined") {
// get (set if not) tab GUID and store in tab session
if (sessionStorage["tabGUID"] == null) sessionStorage["tabGUID"] = tab_GUID();
var guid = sessionStorage["tabGUID"];
// add eventlistener to local storage
window.addEventListener("storage", storage_Handler, false);
// set tab GUID in local storage
localStorage["tabGUID"] = guid;
}
}
function storage_Handler(e) {
// if tabGUID does not match then more than one tab and GUID
if (e.key == 'tabGUID') {
if (e.oldValue != e.newValue) tab_Warning();
}
}
function tab_GUID() {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
s4() + '-' + s4() + s4() + s4();
}
function tab_Warning() {
alert("Another tab is open!");
}
Note: It's IE9+
Hope this helps.
UPDATE - 2020
Client side implementation:
We can make use of Broadcast Channel API which allows communication across browsing contexts (windows, tabs, frames or iframes) provided both contexts are from same origin.
A simple implementation to detect 2nd tab loading the website from the 1st tab:
//in entry point of your app (index.js)
const channel = new BroadcastChannel('tab');
channel.postMessage('another-tab');
// note that listener is added after posting the message
channel.addEventListener('message', (msg) => {
if (msg.data === 'another-tab') {
// message received from 2nd tab
alert('Cannot open multiple instances');
}
});
This doesn't use localStorage or cookies and it even works if 1st tab is offline and 2nd tab is being loaded.
Note: This is not supported in Safari & IE11 yet :(
UPDATE - 2022
From March 2022, it is now officially supported on Safari 🥳
Take a note on its browser compatibility.
However, there's a polyfill available that does the job.
EDIT2:
It's the exact thing which is mentioned at this answer, You need 2 IDs:
One random one
One consistent one (this will be our SSID actually, since you limit tabs of a single browser, it's better to get generated form browser's unique parameters)
You can generate consistent one from browser's user-agent or get it from server-side. store both of them server-side.
Store the random one in window.name property which is tab-specific.
Send a heartbeat every 1~2 seconds to your server containing both consistent ID and random one. if server fails to receive the heartbeat, it cleans up database and de-register dead clients.
on every browser's request, check window.name for the value. if it were missing, check with the server-side whether if the previous tab is closed or not (cleaned from database).
If yes, generate a new pair for client if no, reject them.
Two suggestions on top of my mind:
Server-side (better): provide all your clients, a user name and password. request them on their first visit of your site to enter with their credentials. then on every other request, check for whether user with said credentials is already logged in or not.
Client *
|
|
Server ---> Check whether
Already logged
or not?
______________
| |
yes no
| |
permit reject
them them
Client-side: If you really need a strong check of this, use evercookie to store an already-logged-in cookie on client's machine.
Side-note: Do know that every attempt in client side is not secure at all! client-side should help server-side, it shouldn't be used as the one and only source of security. even evercookies can be deleted so, give my first suggestion a go.
**EDIT:**
Evercookie is really doing a good job at storing most secure zombie cookies ever but since the library itself is a little bit heavy for browsers (storing a cookie takes more than 100ms each time) it's not really recommended for using in real-world web app.
use these instead if you went with server-side solution:
Way around ASP.NET session being shared across multiple tab windows
Kiranvj's answer
Extending rehman_00001's answer to handle the case where you want the alert on the new tabs instead.
const channel = new BroadcastChannel('tab');
let isOriginal = true;
channel.postMessage('another-tab');
// note that listener is added after posting the message
channel.addEventListener('message', (msg) => {
if (msg.data === 'another-tab' && isOriginal) {
// message received from 2nd tab
// reply to all new tabs that the website is already open
channel.postMessage('already-open');
}
if (msg.data === 'already-open') {
isOriginal = false;
// message received from original tab
// replace this with whatever logic you need
alert('Cannot open multiple instances');
}
});
I know this post is pretty old, but in case it helps anybody, I recently looked into basically doing the same thing using localStorage and sessionStorage.
Similar Anthony's answer, it sets an interval to make sure the originating tab keeps the entry fresh, so that if the browser crashes or somehow closes without calling the unload event (included in the comments but not part of the code for testing purposes), then there would just be a short delay before the application would run properly in a new browser window.
Obviously, you would change the "tab is good", "tab is bad" conditions to do whatever logic you want.
Oh, and also, the createGUID method is just a utility to make the session identifier unique... it is from this answer to a previous question (wanted to make sure I wasn't taking credit for that).
https://jsfiddle.net/yex8k2ts/30/
let localStorageTimeout = 15 * 1000; // 15,000 milliseconds = 15 seconds.
let localStorageResetInterval = 10 * 1000; // 10,000 milliseconds = 10 seconds.
let localStorageTabKey = 'test-application-browser-tab';
let sessionStorageGuidKey = 'browser-tab-guid';
function createGUID() {
let guid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
/*eslint-disable*/
let r = Math.random() * 16 | 0,
v = c == 'x' ? r : (r & 0x3 | 0x8);
/*eslint-enable*/
return v.toString(16);
});
return guid;
}
/**
* Compare our tab identifier associated with this session (particular tab)
* with that of one that is in localStorage (the active one for this browser).
* This browser tab is good if any of the following are true:
* 1. There is no localStorage Guid yet (first browser tab).
* 2. The localStorage Guid matches the session Guid. Same tab, refreshed.
* 3. The localStorage timeout period has ended.
*
* If our current session is the correct active one, an interval will continue
* to re-insert the localStorage value with an updated timestamp.
*
* Another thing, that should be done (so you can open a tab within 15 seconds of closing it) would be to do the following (or hook onto an existing onunload method):
* window.onunload = () => {
localStorage.removeItem(localStorageTabKey);
};
*/
function testTab() {
let sessionGuid = sessionStorage.getItem(sessionStorageGuidKey) || createGUID();
let tabObj = JSON.parse(localStorage.getItem(localStorageTabKey)) || null;
sessionStorage.setItem(sessionStorageGuidKey, sessionGuid);
// If no or stale tab object, our session is the winner. If the guid matches, ours is still the winner
if (tabObj === null || (tabObj.timestamp < new Date().getTime() - localStorageTimeout) || tabObj.guid === sessionGuid) {
function setTabObj() {
let newTabObj = {
guid: sessionGuid,
timestamp: new Date().getTime()
};
localStorage.setItem(localStorageTabKey, JSON.stringify(newTabObj));
}
setTabObj();
setInterval(setTabObj, localStorageResetInterval);
return true;
} else {
// An active tab is already open that does not match our session guid.
return false;
}
}
if (testTab()) {
document.getElementById('result').innerHTML = 'tab is good';
} else {
document.getElementById('result').innerHTML = 'tab is bad';
}
window.addEventListener('load', function () {
if (localStorage.getItem('web_browser') == null) {
// new tab
localStorage.setItem('web_browser', 'true');
window.addEventListener('unload', function() {
localStorage.removeItem('web_browser');
})
} else {
// duplicate tab
return;
}
})
Put this script at the beginning of html pages, where you don't want users to duplicate current page or tab.
The same problem (and solution) : https://sites.google.com/site/sarittechworld/track-client-windows
Similar :
http://www.codeproject.com/Articles/35859/Detect-and-prevent-multiple-windows-or-tab-usage-i
The best way to solve this is to have one-time session IDs.
Eg, each page contain a session ID, that is valid for one visit, is unique, and random.
When clicking any one link, it will use & invalidate the session ID, and the new page will have a new session ID.
This will force the user to always browse in the newest window or tab, and also prevents session stealing over the wire.
Any attempt to reuse a old session ID should immediately kill also the active session IDs for that user.
Its also important to store, in the session management system, which pages is accessible from page X. So if page X (with session ID abc) contains links to page 1, 2 and 3, any attempt to visit page 4 with session ID abc, will fail and also kill the session.
This will force the user to always have one single session track, and always follow the logic on the site. Any attempt to go forward, back, using history or log entires, or opening multiple windows or tabs, will fail and logout the user in all windows, tabs and devices.
All this can be completely implemented on server-side, without any client-side logic.
Why do you want to do this?
Could try to do some ugly hacking, but the result would be: There is no way you could completely suppress this behaviour.
This could not be solved by JavaScript, because there is always the possibility that the user has disabled JavaScript in his browser, or allows only a certain subset.
The user could open a new browser, use a different computer, etc. to visit multiple pages at once.
But more important:
Also, your site would be the only site that has this behaviour and for this reason this will confuse everybody which uses your site, because it doesn't work like a web site should work. Everybody who tries to open a second tab will think: "This is odd. This website sucks because it different then websites should be. I will not come again!" ;-)
I wrote this to stop a call center page from being accessed in multiple tabs. It works well and is purely client-side. Just update the else if part to do what you want if it detects a new tab.
// helper function to set cookies
function setCookie(cname, cvalue, seconds) {
var d = new Date();
d.setTime(d.getTime() + (seconds * 1000));
var expires = "expires="+ d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
// helper function to get a cookie
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
// Do not allow multiple call center tabs
if (~window.location.hash.indexOf('#admin/callcenter')) {
$(window).on('beforeunload onbeforeunload', function(){
document.cookie = 'ic_window_id=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
});
function validateCallCenterTab() {
var win_id_cookie_duration = 10; // in seconds
if (!window.name) {
window.name = Math.random().toString();
}
if (!getCookie('ic_window_id') || window.name === getCookie('ic_window_id')) {
// This means they are using just one tab. Set/clobber the cookie to prolong the tab's validity.
setCookie('ic_window_id', window.name, win_id_cookie_duration);
} else if (getCookie('ic_window_id') !== window.name) {
// this means another browser tab is open, alert them to close the tabs until there is only one remaining
var message = 'You cannot have this website open in multiple tabs. ' +
'Please close them until there is only one remaining. Thanks!';
$('html').html(message);
clearInterval(callCenterInterval);
throw 'Multiple call center tabs error. Program terminating.';
}
}
callCenterInterval = setInterval(validateCallCenterTab, 3000);
}

Accessing cookies, hopefully in JavaScript

I am working on a Firefox add-on that will allow users (all of whom are part of a specific group; this add-on is very limited in audience scope) to see the status of their authentication cookie from the status bar. We all have to authenticate to access work-related sites, but we get no warning when the cookie expires, so this causes annoying and sometimes drastic interrupts in work flow. Eventually, this add on will allow us to submit our credentials from the status bar without having to go to do any reloads or redirects, but for now, I just want to see it show the status.
I have been looking at the Mozilla developer pages at nsICookie, nsICookie2, nsICookieManager, etc, and it doesn't make very clear sense how any of it fits into JavaScript or XUL or anything else.
Ideally, I'd just like a way for the JavaScript to go outside of the document and get the cookie string for a domain I specify. If I could do that, it would allow the code to possibly be ported over to other browsers (Safari and Chrome, in particular). But if this must be browser specific, then I would at least like to know the method for checking if the cookie exists in Firefox without any bells and whistles of setting or removing.
Simply put, I want a way to say:
if (cookieExists("sample.com", CookieName)) {
alert("You're signed in!");
} else {
alert('Go sign in, you fool!');
}
What is the easiest/most portable way of doing this (browser-side, of course)?
I have been looking at the Mozilla developer pages at nsICookie, nsICookie2, nsICookieManager, etc, and it doesn't make very clear sense how any of it fits into javascript or XUL or anything else.
access to all cookies from Firefox extension is possible and uses the nsICookieManager and nsICookie interfaces. From javascript code in your extension, you access the cookie manager with
var cookieManager = Components.classes["#mozilla.org/cookiemanager;1"].getService(Components.interfaces.nsICookieManager);
and than you can iterate through all stored cookies
var enum = cookieManager.enumerator;
while (enum.hasMoreElements()){
var cookie = enum.getNext();
if (cookie instanceof Components.interfaces.nsICookie){
// commands
}
}
now, when having reference to cookie object you can check its properties
cookie.host
cookie.name
cookie.value
...
defined in nsICookie interface. This code is Firefox specific and can be run as a browser extension or signed script. Hope my explanation helped a bit.
Below I present some links on using JS XPCOM interfaces in extensions:
JS XPCOM
Using cookies
you can use jquery plugin for cookie handling
http://www.stilbuero.de/2006/09/17/cookie-plugin-for-jquery/
or simply through javascript :
http://www.quirksmode.org/js/cookies.html
Here's a nice tutorial for working with cookies in javascript. Using the functions from that tutorial, you could probably do something like this:
if readCookie(yourCookieName != "") {
alert("You're signed in!");
else {
alert("Go sign in, you fool!");
}
Here are the cookie functions:
function readCookie(name) {
var ca = document.cookie.split(';');
var nameEQ = name + "=";
for(var i=0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1, c.length); //delete spaces
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return "";
}
function createCookie(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function eraseCookie(name) {
createCookie(name, "", -1);
}

Categories

Resources