[SalesForce] How to remove item from localStorage

I need one help. I am using next and previous custom buttons on account detail page to navigate through selected account record from list view without going back to list. For this, i stored selected account record ids into local storage. This is working perfectly. but if i manually open a account record (not from list view) and click on next button than it should show pop up message as 'This was the Last Account!'. But it's showing the Account records which I selected earlier from list view of Account.
For this i want to remove record ids after navigation to that page from localstorage, its not working.

Please see below code to store ids in local storage.

var accounts = {!GETRECORDIDS( $ObjectType.Account )};
if(accounts .length >= 1){
   localStorage['Accounts '] = accounts ;
alert(localStorage['Accounts']);
   location.replace('/' + accounts [0]);
   }

The code on next account button is-

if(localStorage['Accounts']){
    var accounts = localStorage['Accounts'].split(',');
    var accountsPos = accounts .indexOf('{!Account.Id}');

    if(accountsPos == accounts.length - 1){ 
        alert('Last Account!');
    }
    else{
        location.replace('/' + accounts[accountPos + 1]);
    }
}

Please help.

Best Answer

The difficult part is not about how to clear localStorage, it is about where to inject the javascript code. Anyway, I will put the clear local storage code here first. You can use either:

window.localStorage.clear();

Or

localStorage.removeItem("Accounts");

So coming to the major part of it. I guess the you are adding two buttons in a standard Account page and the clear piece of code should be executed during the onload time of the page. So there isn't much good way of doing it.

One solution I can think about is create an empty Visualforce page and add it into your standard page layout. And you can clear your localStorage inside that empty VF page. That's the only approach I can think of.

Edit

As you only want to remove the specific Account, you can use the following code:

var accountsPos = accounts.indexOf('{!Account.Id}');
if(accountsPos > -1) {
    accounts.splice(accountsPos, 1);
    localStorage['Accounts '] = accounts ;
}
Related Topic