Uniquely identify a duplicated Chrome tab - javascript

I am currently using window.sessionStorage to store a uniquely generated session ID. This ID is passed to all ajax calls to the server and persists across page navigation and reloads.
This seems to work perfectly for my target browsers, with one caveat: the duplicate tab functionality in Chrome.
Duplicating the tab copies the session storage to the new tab. When the new tab loads and communicates with the server, it now has the same "unique" identifier as the duplicated target tab.
Are there any ways that I can distinguish between the two duplicated tabs?
Or are they truly duplicates and no information is different between the two?
Nothing persists after the tab/window is closed, so even a simple numeric tab id or anything would work as long as it is unique for that current instance.

A variant of this worked for me:
https://stackoverflow.com/a/60164111/13375384
The trick is to only put the ID in session storage for the brief period of time when the tab is refreshing
In my TypeScript project, the solution looked like this:
const tabIdKey = "tabIdStorageKey"
const initTabId = (): string => {
const id = sessionStorage.getItem(tabIdKey)
if (id) {
sessionStorage.removeItem(tabIdKey)
return id
}
return uuid()
}
const tabId = initTabId()
window.addEventListener("beforeunload", () => {
sessionStorage.setItem(tabIdKey, tabId)
})

Session storage is on the browser level, and not on the tab level. See https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage .
The only method I know of to identify a tab is to pass a paramater at the end of each URL (and even so you would need to use JavaScript to prevent open in new Tab).
Other methods would be unbearable, such as embedding an iframe in the app (and storing the identifier in the parent), but possible.
In short, you should rephrase you question to simply identifying a tab, and you will nevertheless not find an answer.

My eventual solution to this was to generate a unique ID on the server side which gets stored in the server session and passed back to be stored in sessionStorage. I also have another value (let's call it FOO) that is set on the client side and stored.
Pretend it looks like this in a map:
{
"unique_id" : "ABC123",
"FOO" : "some value"
}
I send the values up to the server with every ajax request.
On page load, I check to see if I already have the unique_id, FOO pair in sessionStorage and load them. Any time the value of FOO changes, it will get compared with the server pair. If it has a different value then I store the new value for FOO under a new unique ID and hand it back to the client.
This doesn't 100% solve the problem, but it does make sure that FOO, which represents some persistent state, is never used incorrectly after tab duplication.
The tab that originally had had the unique_id, FOO pair will continue to have that pair while the duplicated tab will have a new pair.
Technically, until the value of FOO changes the two tabs share the same unique_id, but as long as unique_id gets reassigned when FOO changes, they won't overwrite each other's state within the server session.

Related

Storing a HTML OBJECT Array inside Chrome Storage for a Chrome Extension

BACKGROUND:
I'm writing a chrome extension that when you access a certain page it finds all the table rows and then stores them and when you go back it shows you all the new values that have been added.
I want to store an array in storage so that when the user comes back to the page I can access it. Mainly to compare results each time to see if anything has changed.
Example.
myArray = [HTML OBJECT, HTML OBJECT, HTML OBJECT];
on.window.unload {
Chrome.storage.set(STORE MY ARRAY)
}
on.windows.onload {
chrome.storage.get(MY STORED ARRAY AND SET TO OLD_myArray[])
}
function compareArrays() {
TO DO STUFF WITH MY myArray[] and OLD_myArray[]
e.g. comparing values to see if anything has changed.
}
I've tried local Storage but realised that It doesn't store arrays, So moved to Chrome storage.
I would like help getting myArray to store itself on unload and then set itself to OLD_myArray onload, So I can compare the values for the differences. Thanks.
In order to use chrome.storage, you need to use one of two methods:
chrome.storage.sync, which syncs saved data to any browser the user logs into.
chrome.storage.local, which only saves data to the current machine.
As the official documentation discusses, chrome.storage is implemented with callbacks, not with a return value from the get or set call itself.
// Save the current myArray value.
chrome.storage.local.set({'storedArray': myArray}, function() {
console.log(`storedArray now contains ${myArray}.`);
});
// Retrieve the the stored value, defaulting to an empty array.
chrome.storage.local.get({'storedArray': []}, function(data) {
console.log(`storedArray's value is ${data.storedArray}.`);
});
As an aside, it may not be a great idea to attach storage functions to an unload event, as the browsing context could terminate before the operation is complete. A browser crash, for instance, wouldn't call the window.unload event (this is only one of a number of situations which would interfere with your handler).

Attempting to use a global array inside of a JS file shared between 2 HTML files and failing

So I have one HTML page which consists of a bunch of form elements for the user to fill out. I push all the selections that the user makes into one global variable, allTheData[] inside my only Javascript file.
Then I have a 2nd HTML page which loads in after a user clicks a button. This HTML page is supposed to take some of the data inside the allTheData array and display it. I am calling the function to display allTheData by using:
window.onload = function () {
if (window.location.href.indexOf('Two') > -1) {
carousel();
}
}
function carousel() {
console.log("oh");
alert(allTheData.toString());
}
However, I am finding that nothing gets displayed in my 2nd HTML page and the allTheData array appears to be empty despite it getting it filled out previously in the 1st HTML page. I am pretty confident that I am correctly pushing data into the allTheData array because when I use alert(allTheData.toString()) while i'm still inside my 1st HTML page, all the data gets displayed.
I think there's something happening during my transition from the 1st to 2nd HTML page that causes the allTheData array to empty or something but I am not sure what it is. Please help a newbie out!
Web Storage: This sounds like a job for the window.sessionStorage object, which along with its cousin window.localStorage allows data-as-strings to be saved in the users browser for use across pages on the same domain.
However, keep in mind that they are both Cookie-like features and therefore their effectiveness depends on the user's Cookie preference for each domain.
A simple condition will determine if the web storage option is available, like so...
if (window.sessionStorage) {
// continue with app ...
} else {
// inform user about web storage
// and ask them to accept Cookies
// before reloading the page (or whatever)
}
Saving to and retrieving from web storage requires conversion to-and-from String data types, usually via JSON methods like so...
// save to...
var array = ['item0', 'item1', 2, 3, 'IV'];
sessionStorage.myApp = JSON.stringify(array);
// retrieve from...
var array = JSON.parse(sessionStorage.myApp);
There are more specific methods available than these. Further details and compatibility tables etc in Using the Web Storage API # MDN.
Hope that helps. :)

Unable to set selected attribute after page loads

My html page with SELECT and OPTIONS values sets one of the options as a default.
Were the user to choose a different option, which then takes him to a new page, I’d like to preserve that value so the next time home page is generated the value the user selected should remain on display, rather than the original default value, when the window reloads.
How do I do this in javascript?
I had tried to save values via a DOM capture of the selected value, but I don’t seem to be able to change that original default value.
E.g.,, one line of code reads:
window.location.reload();
yet were I to use “hold values” to capture the user’s selected option that differs from the default option, like so:
var holdPick = document.getElementById(“uPick”).value;
window.location.reload();
document.getElementById(“uPick”).value = holdPick;
that won’t do the trick, and I know not why.
When you reload a page, all the JavaScript is reloaded too. So, that's why the JavaScript snippet you posted doesn't seem to be working... The line after window.location.reload(); isn't even run at all. If you want to have a value that persists between page loads, you'll need to set and retrieve a cookie. Check out the JavaScript document.cookie API at MDN. That should tell you what you need to know about storing and retrieving your value in a cookie.
Why: every time var holdPick is executed it will create variable from scratch.
Second line tells the browser to reload page, so the third line never gets the chance to be executed.
I'd recommend usage of HTML5 Web Storage
if (sessionStorage.uPick) { //check if variable has been set already
document.getElementById(“uPick”).value = sessionStorage.uPick;
} else {
sessionStorage.clickcount = document.getElementById(“uPick”).value;
}
you can use cookies also, but I don't think it is as straight forward.

Losing context reference

I am encountering a 'small' problem when making a new object in the options page.
In the options page I create a few objects and save them as general settings. These objects have method to communicate with different API's. But as soon as I get one of those objects to work with, I lose the context on the page I am.
For example:
The options page I create an object that has a method 'request' and I send an ajax request to some api with this method. When I call this on an other page the ajax request is logged within the options page. When I close the options page I lose all context of the logs it makes.
Is there a way to force the context reference to the current page? or did I make a mistake with creating objects on the wrong pages/saving them and retrieving them on a page that needs them? (IE Should I only save the data I need to create objects on the page itself? (which seems like alot of overhead for the the same thing(?)).
Thanks in advance.
EDIT
I have an option page which creates an Object lets call it MyApi. I create a new MyApi and store it in chrome.storage.local . When a user has some text selected and clicks on the context menu I open a new page(selectedText.html) which shows the selected text and some API calls are made, which are mostly ajax requests. The moment I get the object from storage in selectedText.html and make any request with MyApi I see no logs in the network tab of the ajax requests, neither any console logs. But with my options page open I see everything in there.
EDIT2
save : function()
{
var obj = {'api':this.data};
chrome.storage.local.set(obj,function() { if(chrome.runtime.lastError) console.warn(chrome.runtime.lastError); });
}
This is in the background script.
You could achieve what you want this way:
Define your object/function/whatever in the background page.
Use chrome.runtime.getBackgroundPage() to get a hold on the background pages window object.
Execute the desired method, passing as argument an object of the local context. (Of course you have to modify the function to accept and make use of such an argument.)
Example:
In background.js:
function myFunc(winObj, msg) {
winObj.console.log(msg);
}
In otherPage.js:
chrome.runtime.getBackgroundPage(function(bgPage) {
bgPage.myFunc(window, "This will be logged in 'otherPage.html' !");
});
It is not the cleanest solution, but it might work...

Change the URL in the browser without loading the new page using JavaScript

How would I have a JavaScript action that may have some effects on the current page but would also change the URL in the browser so if the user hits reload or bookmark, then the new URL is used?
It would also be nice if the back button would reload the original URL.
I am trying to record JavaScript state in the URL.
If you want it to work in browsers that don't support history.pushState and history.popState yet, the "old" way is to set the fragment identifier, which won't cause a page reload.
The basic idea is to set the window.location.hash property to a value that contains whatever state information you need, then either use the window.onhashchange event, or for older browsers that don't support onhashchange (IE < 8, Firefox < 3.6), periodically check to see if the hash has changed (using setInterval for example) and update the page. You will also need to check the hash value on page load to set up the initial content.
If you're using jQuery there's a hashchange plugin that will use whichever method the browser supports. I'm sure there are plugins for other libraries as well.
One thing to be careful of is colliding with ids on the page, because the browser will scroll to any element with a matching id.
With HTML 5, use the history.pushState function. As an example:
<script type="text/javascript">
var stateObj = { foo: "bar" };
function change_my_url()
{
history.pushState(stateObj, "page 2", "bar.html");
}
var link = document.getElementById('click');
link.addEventListener('click', change_my_url, false);
</script>
and a href:
<a href="#" id='click'>Click to change url to bar.html</a>
If you want to change the URL without adding an entry to the back button list, use history.replaceState instead.
window.location.href contains the current URL. You can read from it, you can append to it, and you can replace it, which may cause a page reload.
If, as it sounds like, you want to record javascript state in the URL so it can be bookmarked, without reloading the page, append it to the current URL after a # and have a piece of javascript triggered by the onload event parse the current URL to see if it contains saved state.
If you use a ? instead of a #, you will force a reload of the page, but since you will parse the saved state on load this may not actually be a problem; and this will make the forward and back buttons work correctly as well.
I would strongly suspect this is not possible, because it would be an incredible security problem if it were. For example, I could make a page which looked like a bank login page, and make the URL in the address bar look just like the real bank!
Perhaps if you explain why you want to do this, folks might be able to suggest alternative approaches...
[Edit in 2011: Since I wrote this answer in 2008, more info has come to light regarding an HTML5 technique that allows the URL to be modified as long as it is from the same origin]
jQuery has a great plugin for changing browsers' URL, called jQuery-pusher.
JavaScript pushState and jQuery could be used together, like:
history.pushState(null, null, $(this).attr('href'));
Example:
$('a').click(function (event) {
// Prevent default click action
event.preventDefault();
// Detect if pushState is available
if(history.pushState) {
history.pushState(null, null, $(this).attr('href'));
}
return false;
});
Using only JavaScript history.pushState(), which changes the referrer, that gets used in the HTTP header for XMLHttpRequest objects created after you change the state.
Example:
window.history.pushState("object", "Your New Title", "/new-url");
The pushState() method:
pushState() takes three parameters: a state object, a title (which is currently ignored), and (optionally) a URL. Let's examine each of these three parameters in more detail:
state object — The state object is a JavaScript object which is associated with the new history entry created by pushState(). Whenever the user navigates to the new state, a popstate event is fired, and the state property of the event contains a copy of the history entry's state object.
The state object can be anything that can be serialized. Because Firefox saves state objects to the user's disk so they can be restored after the user restarts her browser, we impose a size limit of 640k characters on the serialized representation of a state object. If you pass a state object whose serialized representation is larger than this to pushState(), the method will throw an exception. If you need more space than this, you're encouraged to use sessionStorage and/or localStorage.
title — Firefox currently ignores this parameter, although it may use it in the future. Passing the empty string here should be safe against future changes to the method. Alternatively, you could pass a short title for the state to which you're moving.
URL — The new history entry's URL is given by this parameter. Note that the browser won't attempt to load this URL after a call to pushState(), but it might attempt to load the URL later, for instance after the user restarts her browser. The new URL does not need to be absolute; if it's relative, it's resolved relative to the current URL. The new URL must be of the same origin as the current URL; otherwise, pushState() will throw an exception. This parameter is optional; if it isn't specified, it's set to the document's current URL.
Browser security settings prevent people from modifying the displayed url directly. You could imagine the phishing vulnerabilities that would cause.
Only reliable way to change the url without changing pages is to use an internal link or hash. e.g.: http://site.com/page.html becomes http://site.com/page.html#item1 . This technique is often used in hijax(AJAX + preserve history).
When doing this I'll often just use links for the actions with the hash as the href, then add click events with jquery that use the requested hash to determine and delegate the action.
I hope that sets you on the right path.
There is a Yahoo YUI component (Browser History Manager) which can handle this: http://developer.yahoo.com/yui/history/
Facebook's photo gallery does this using a #hash in the URL. Here are some example URLs:
Before clicking 'next':
/photo.php?fbid=496429237507&set=a.218088072507.133423.681812507&pid=5887027&id=681812507
After clicking 'next':
/photo.php?fbid=496429237507&set=a.218088072507.133423.681812507&pid=5887027&id=681812507#!/photo.php?fbid=496435457507&set=a.218088072507.133423.681812507&pid=5887085&id=681812507
Note the hash-bang (#!) immediately followed by the new URL.
A more simple answer i present,
window.history.pushState(null, null, "/abc")
this will add /abc after the domain name in the browser URL. Just copy this code and paste it in the browser console and see the URL changing to "https://stackoverflow.com/abc"
There's a jquery plugin http://www.asual.com/jquery/address/
I think this is what you need.
What is working for me is - history.replaceState() function which is as follows -
history.replaceState(data,"Title of page"[,'url-of-the-page']);
This will not reload page, you can make use of it with event of javascript
I was wondering if it will posible as long as the parent path in the page is same, only something new is appended to it.
So like let's say the user is at the page: http://domain.com/site/page.html
Then the browser can let me do location.append = new.html
and the page becomes: http://domain.com/site/page.htmlnew.html and the browser does not change it.
Or just allow the person to change get parameter, so let's location.get = me=1&page=1.
So original page becomes http://domain.com/site/page.html?me=1&page=1 and it does not refresh.
The problem with # is that the data is not cached (at least I don't think so) when hash is changed. So it is like each time a new page is being loaded, whereas back- and forward buttons in a non-Ajax page are able to cache data and do not spend time on re-loading the data.
From what I saw, the Yahoo history thing already loads all of the data at once. It does not seem to be doing any Ajax requests. So when a div is used to handle different method overtime, that data is not stored for each history state.
my code is:
//change address bar
function setLocation(curLoc){
try {
history.pushState(null, null, curLoc);
return false;
} catch(e) {}
location.hash = '#' + curLoc;
}
and action:
setLocation('http://example.com/your-url-here');
and example
$(document).ready(function(){
$('nav li a').on('click', function(){
if($(this).hasClass('active')) {
} else {
setLocation($(this).attr('href'));
}
return false;
});
});
That's all :)
I've had success with:
location.hash="myValue";
It just adds #myValue to the current URL. If you need to trigger an event on page Load, you can use the same location.hash to check for the relevant value. Just remember to remove the # from the value returned by location.hash e.g.
var articleId = window.location.hash.replace("#","");

Categories

Resources