HTML5 Local Storage VS App Cache Offline Website Browsing - javascript

After going through multiple articles,
I am still not clear on the difference between Local Storage and App Cache Manifest.
Also referred: Is AppCache = Application Cache = Web Storage's LocalStorage? (SO 10986026), Application Cache is a Douchebag (A List Apart)
My AIM is to build a website with specific pages be allowed offline to user on user demand.
Steps followed :
I opened a site on Chrome : http://www.spritecow.com/
And checked AppCache : chrome://appcache-internals/
And the site was cached.
I closed Chrome and reloaded it. The cache was still there. Exactly what I need for offline browsing
Now how is this different from local storage? Tried to find the difference but all sites answer in purpose, i.e. AppCache for templates' caching and Local Storage for content within the template.
Certain sites do not prefer AppCache as it reloads entire cache for a single line change. Certain sites prefer only local storage. While some go for the combo of AppCache(template) and Localstorage.
Now the doubt is :
Local storage stores on client machine. How does AppCache storage is different if I can still access it even browser is closed.
As clearing cache will clear AppCache then i'd go for only Local Storage.
What is the best practice to be followed for offline browsing? I am completely new to this and need a little clarity on the same
EDIT
The doubt is not answered by the link (Is AppCache = Application Cache = Web Storage's LocalStorage?) as this gives difference but not based on the purpose of Offline Browsing Practices (which is the aim for this doubt).

AppCache use a manifest file to define what files used by the app should be stored (You can cache files and ressources like HTML pages, JS scripts, CSS styles, images,...)
LocalStorage will store data but not pages. So every javascript object that you can stringify can be stored in the localStorage.
So AppCache and localStorage aren't the same, but they are complementary.
Example
Imagine a web calendar that you want to be available offline (note: for this example, we use here a static page and data are loaded with javascript. The same can be made from a dynamic page, but this example use static).
The appcache will store the html page and the ressources that it uses (javascripts, css, images) to render you page.
As you have put in your manifest file everything to be cached for the next offline access, the pages are stored and you'll be able to display your page offline at the next visit.
But problem, your calendar is displayed but is empty. All meetings and events of the month aren't there. This is because your page is stored, but you still need network to load the meetings in your calendar. And as you're offline, you have no network...
If you want to have all your meetings available offline too, you'll have to store them in the localstorage (not in the appCache, because it's not a page, it's data accessed by JavaScript.)
So you will need to change your Javascript function from this :
function initApp() {
var data = loadDataWithAjax();
renderPlanning(data);
}
to this
function initApp () {
var data;
if(offline) {
data = loadFromLocalStorage();
} else {
data = loadDataWithAjax();
storeDataInLocalStorage(data);
}
renderPlanning(data);
}

Appcache will even work if you are totally offline and your browser is closed and then you open your browser and type in the URL while still offline — the page loads! Check this site here … load it once while online and then disconnect from the Internet and close your browser … and then reopen browser and try to visit it while still offline.
localStorage needs connection first to load the js code needed to get the data from it.

Related

Saving Local Application Settings

Is there any way to safely retain/save data (settings) other than IndexedDB and manual saving (prompt the user with a dialog box to save)?
Basically I am writing an offline application and will be bundled and deployed as a local html file (e.g. file:///D:/test/index.html, no servers, just run by double-clicking the html file). It will have some settings and I need to be able to save these settings locally. The first time the app boots up, I retrieve the settings from a app-settings.json file and save it to IndexedDB.
However, my problem is that when the user clears the browser data, the settings will be deleted as well.
I do not want to prompt the user with a dialog box asking to save the app-settings.json everytime an update is made to the settings. (It would also be prone to duplicate, misplaced settings)
Any suggestion on how to go about this? How can I safely retain the application settings without any servers? Maybe there is an offline database of some sort that can be used in scenarios like this?
Would appreciate any help here! I'm desperately out of ideas :(
Thank you!
// Check if site's storage has been marked as persistent
if (navigator.storage && navigator.storage.persist) {
const isPersisted = await navigator.storage.persisted();
console.log(`Persisted storage granted: ${isPersisted}`);
}
please enable persistent storage by enabling navigator.storage.persist, and I would suggest start using service workers to manage offline applications.
https://web.dev/persistent-storage/
https://developers.google.com/web/fundamentals/primers/service-workers
You Can use the
Use the Javascript File Api
https://developer.mozilla.org/en-US/docs/Web/API/File_and_Directory_Entries_API
The dialog to save the file will be shown once,
Then reading the file will not require a file dialog.
BTW
VS Code web also uses the api: https://vscode.dev/

How can Chrome Extension talk to itself when installed by different users?

The Chrome browser supports multiple users (personas), so we can load a web page with different cookies and session data. This is working great, doing what I want. Now I wish for an extension installed on multiple user accounts to share information between users.
I cannot see how to do this, help please?
Details and Ideas:
By setting some cookies I can change some preferences of the target web page, to use some new features. Some features are different, but the core information should be the same. I wish to compare them via extension code.
By using the people feature of the chrome browser, ( personas ) I can load both old and new versions of our web page in chrome, and compare side by side.
I also have a chrome extension which scrapes a target web page, to pull out information like names, prices, information. This is also working great. I can manually check the scrape results of old or new versions of the page.
Now for the challenge : How can I compare scrape results between web pages loaded on different people (personas). Each "people" has the extension installed and running.
When I send an external message using the extension ID, only extensions on the same "people" receive it.
When I look at the background pages for each "people" extension, they are different. Setting a value for my Extension in one does not affect my Extension in the other.
// code in background page.
chrome.runtime.onMessageExternal.addListener(
function(request, sender, sendResponse){
console.log('background page was hit');
});
// paste code in browser console.
chrome.runtime.sendMessage('id_here', {getTargetData: true},
function(response) {
console.log(response);
});
You can't share data between users on the client. This would allow your extension to potentially download all of a user's data and share it with another user.
That said, you can just push the data to a shared server and use that to compare (using HTTP or Websockets)

Get localStorage from within extension without loading a page

I know how to get the localStorage from any open wep page by using content scripts. So I'm basically able to open a new tab with my own web page and read the storage data with a content script and message it to the background page.
But now I'd like to do this without loading an external page every time. Is there a way to access the localStorage of a page directly from within the extension? Maybe some query to chrome directly.
I don't see any API for that.
Your options are:
Make a native messaging host application that would read database files directly from Local Storage directory in the browser user profile. An example: What's the best way to read Sqlite3 directly in Browser using Javascript?
Put the other page into an iframe: Is it possible to use HTML5 local storage to share data between pages from different sites?
P.S. "Ironic side note" quoted from Cross-domain localStorage article by Nicholas C. Zakas.
Who knew cross-domain client-side data storage would be useful? Actually, the WHAT-WG did. In the first draft of the Web Storage specification (at that time, part of HTML5), there was an object called globalStorage that allowed you to specify which domains could access certain data. [...]
The globalStorage interface was implemented in Firefox 2 prematurely as the specification was still evolving. Due to security concerns, globalStorage was removed from the spec and replaced with the origin-specific localStorage.

Reading cache using JavaScript

This is Two questions:
1/ How can I read the cache stored by the browser if there's no permission restrictions?
2/ If the user browse into a website, is there a posibility of storing the page source code [HTML] in cache? (big website like youtube ..etc)
Thanks.
There is no way to read the cache manually - it all happens behind the scenes, if there is cache.
Yes, you can store the website's source code to the browser cache, but only the client-side part - HTML/CSS/JS/images/fonts/etc. It's called HTML5 Application Cache and it consists in a simple manifest file, which instructs the browser to download certain files locally and next time load them instead of downloading again. This cache you can programmatically update. Keep in mind, though, that most browsers have a limit (usually 5MB) of how much data you can store.
Hope that helps.

Share in-memory objects in Chrome extension content scripts?

I am new to both JavaScript and Chrome development, and am trying to create an extension that injects content/CSS in certain web pages. Simple enough, but the catch is that to do so it requires looking through a significant amount of data in local storage. From what I've read so far, the correct way to do this would be either:
Reading the required data (JSON serialized) from storage directly from the content script every time the page is visited, or
Maintaining the state in the extension background page and transferring the required data (also JSON serialized) to the content script environment using message passing.
Either of these approaches, however, would be extremely inefficient due to large amounts of data being needlessly serialized and deserialized on every page load.
So, I want to know:
Is it in any way possible to maintain a shared memory cache in Chrome that content scripts injected in all tabs can access?
If not, is an alternate approach possible where the background page listens for the chrome.tabs.onUpdated event and somehow modifies the target DOM itself?
1) I don't think this is possible. You seem to have exhausted the possibilities.
2) Content scripts are the only way to access/modify a normal tab's DOM.
1- Reading the required data (JSON serialized) from storage directly from the content script every time the page is visited.
But you have to do that every time your page is loaded which you want to avoid (I guess)
2- Maintaining the state in the extension background page and transferring the required data (also JSON serialized) to the content script environment using message passing.
The only way to make Content Scripts and Background scripts interact is via Message Passing. You are not actually looking to an alternative solution but you want to improve the process and avoid message passing each time a page is loaded.
For this, you can develop a spec. The spec states for which URLs or which Domains or based on some condition you want to get the data from Background. If your current URL/Tab agrees with spec only then pass a message to background.
Optionally, Background can also do the same and send message only if your spec is followed. Moreover, when your extension is loaded, you can also cache the storage into local variable.
Use Chrome Storage API to listen for changes in storage and update your local data copy accordingly.
You can also look at this code written by me using the same approach.

Categories