Clear browser website data when update javascript/jquery code - javascript

I'm building a asp.net website (use HTML, C#, Jquery ..).
Then. Website is published.
Then. I have some bug need to fix in javascript code file.
I fixed it and republished website.
But, browser save cache or another browsing data, and the user did not get fixed version.
So, how can I clear browsing data or cache of user manually (by javascript, jquery or C#) when I change some litle code or fix small bug in js file? I cannot say with user so "U must clear browsing data to get new version !"
Thanks.

This may not directly answer your question but if you are using any bundler like webpack or task runner like gulp, you can actually generate the file with a hashkey.
for example the bundler will generate a production version of the js file as
myFile.d587bbd6e38337f5accd.js
d587bbd6e38337f5accd is the hash key generated by the bundler & it will be injected by the bundler itself. In such case every release will have a js file with modified hash key. So it wont load from cache
You can check this LINK to know about it

In case of javascript use cacheBustingUrl whose format is given below which is append to Date.Now() which will solve the problem of caching.
<script>
var scriptUrl = "/site/js/script.js",
cacheBustingUrl = scriptUrl + "?" + Date.now(),
newScriptElement = document.createElement("script");
newScriptElement.setAttribute("src",cacheBustingUrl);
document.body.appendChild(newScriptElement);
</script>
This should append a new script element like
<script src="/site/js/script.js?1404918388711"></script>
to the end of the page, which the browser will load like any other script tag.

You can try setting a refresh on your page using window.location.reload(true) in theory this will ignore all the cached files and retrieve new copies of your website to the user.
Maybe create check that will refresh the page if its not up to date.

no browser can allow you to remove its cache.its a very big security aspect but you can prevent cashing by passing this meta in your HTML
<meta http-equiv='cache-control' content='no-cache'>
<meta http-equiv='expires' content='0'>
<meta http-equiv='pragma' content='no-cache'>
Also You have to turn off auto complete textbox by
formname.setAttribute( "autocomplete", "off" );

Related

Force browser to reload the Javascript files

I am trying to achieve the below in ASP.NET MVC3 web application which uses razor.
1) In my Index.cshtml file, I have the below reference.
<script src="/MySite/Scripts/Main.js"></script>
2) I load my home page for the first time and a http request is made to fetch this file which returns 200.
3) Then, I made some changes to the Main.js and saved it.
4) Now I just reload the home page (please note that I am not refreshing the page) by going to the address bar and typing the home page url and pressing enter. At this point, I want the browser to fetch the updated Main.js file by making a http request again.
How can I achieve this? I don't want to use System.Web.Optimization bundling way. I knew that we can achieve this by changing the URL (appending version or some random number) everytime the file changes.
But the challenge here is the URL is hardcoded in my Index.cshtml file. Everytime when there is a change in Main.js file, how can I change that hardcoded URL in the Index.cshtml file?
Thanks,
Sathya.
What I was trying to achieve is to invalidate browser cache as soon as my application javascript file (which already got cached in the browser) gets modified at the physical location. I understood that this is simply not achievable as no browsers are providing that support currently. To get around this below are the only two ways:
1)Use MVC bundling
2)Everytime the file is modified, modify the URL by just appending the version or any random number to the URL through querystring. This method is explained in the following URL - force browsers to get latest js and css files in asp.net application
But the disadvantage with the 2nd method is, if there are any external applications referring to your application's javascript file, the browser cache will still not be invalidated without refreshing the external application in browser.
Just add a timestamp as a querystring parameter:
var timestamp = System.DateTime.Now.ToString("yyyyMMddHHmmssfff");
<script src="/MySite/Scripts/Main.js?TimeStamp=#timestamp"></script>
Note: Only update TimeStamp parameter value, when the file is updated/modified.
It's not possible without either using bundling (which internally handles version) or manually appending version. You can create a single file bundle as well if you want.

Caching JS without changing the file name or clearing cache locally

I'm working on a project, which has no way to implement versioning on my js files for cache.
Therefore I need a way to update users cache from the server side, if possible.
My thinking is that I can change the name of the js temporarily, then let the browser cache the new instance. Then I will revert the file name to what it was.
At this point does this mean that the browser will still have a cache of the old filename therefore loading the old js?
e.g.
example.js > changes to > example-new.js > browser caches this new js > revert the filename back to example.js > ...... what happens?
If your case is to change js code on the server side and then make this changes available to the clients without the need of "clear cache" then do the following.
Instead of changing the filenames, reference them with an extra parameter, lets say using the version.
So lets say you reference a js file "example.js" within your html,jsp .... page.
your tag should be like: (note the ?v1.1 at the end of the file url)
<script type="text/javascript" src="jslib/example.js?v1.1"></script>
Now next time you make changes to this file, reference it like:
<script type="text/javascript" src="jslib/example.js?v1.2"></script>
This will force client browser to get the new file instead of using the cached one.

Phantomjs: Modifying html dom before opening it as webpage

I need to process html files that have corrupted script files that are added to it via tag.
Im planning to remove all script tag present in the webpage via phantomjs.
But on opening the webpage via webpage.open(), phantomjs parse error is thrown since it cannot parse the JS content within the script tag.
Here is an example:
<html>
<head>
<script>
corrupted JS
if(dadadd
;
</script>
<body>
some content
</body>
</html>
Can someone help me on suggesting the right way to clean this webpage using phantomjs ?
It's not (easily) possible. You could download (not through opening the page, but rather making an Ajax request in page.evaluate()) the static html, then change according to your needs, then assign it to page.content.
This still might not work, because as soon as you assign it to page.content, you're saying that PhantomJS should interpret this source as a page from an unknown domain (about:blank). Since the page source contains all kinds of links/scripts/stylesheets without a domain name, you'll have to change those too in order for the page to successfully load all kinds of resources.
It might be easier to just have a proxy between PhantomJS and the internet with a custom rule to adjust the page source to your needs.

How to save scripts, images and css files into browser cache?

I have been trying to enable Caching for my web-page. I find-out so much post related to Caching static file in browser cache, but i did't get success.
I try for both server side or client side code for it:
SERVER SIDE
I tried to put code for set-up a "Cache-Control" header on server side page-load(write code in C#) :
DateTime dt = DateTime.Now.AddMinutes(30);
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.Public);
HttpContext.Current.Response.Cache.SetExpires(dt);
HttpContext.Current.Response.Cache.SetMaxAge(new TimeSpan(dt.Ticks - DateTime.Now.Ticks));
Reference
CLIENT SIDE
In javascript after some googling i find a "Preloading images" technique , but applying this code also not give me correct solution of storing file into cache.
Reference
HTML META TAGS
Added following tags in my page header:
<meta http-equiv="Cache-control" content="private"/>
<meta http-equiv="EXPIRES" content="Wed, 16 oct 2013 11:12:01 GMT"/>
did't get success.
Reference
Can any one tell me what i am doing wrong here?
And any one suggest me for perfect solution/full tutorial for enabling cache to store static files into browser cache.
Thanks in advance....!!!!
First i think you have confused caching with preloading images.
If what you really need is caching, check your browser whether caching is disabled.Because scripts,images and css are cached defaultly by browser.
Next how did you check whether those are cached?
You could use "cache-manifest" which uses AppCache of the browser.
It allows you to run your website offline also.
Head to http://diveintohtml5.info/offline.html for more information.
Hope it helps!!

How to download the current page as a file / attachment using Javascript?

I am aware of the hidden iFrame trick as mentioned here (http://stackoverflow.com/questions/365777/starting-file-download-with-javascript) and in other answers.
I am interested in a similar problem:
How can I use Javascript to download the current page (IE: the current DOM, or some sub-set of it) as a file?
I have a web page which fetches results from a non-deterministic query (eg. a random sample) to display to the user. I can already, via a querystring parameter, make the page return a file instead of rendering the page. I can add a "Get file version" button (our standard approach) but the results will be different to those displayed because it is a different run of the query.
Is there any way via Javascript to download the current page as a file, or is copying to the clipboard my only option?
EDIT
An option suggested by Stefan Kendall and dj_segfault is to write the result server side for later retrieval. Good idea, but unfortunately writing files server side is out of the question in this instance.
How about shudder passing the innerHTML as a post parameter to another page?
You can try with the protocol data:text/attachment
Like in:
<html>
<head>
<style>
</style>
</head>
<body>
<div id="hello">
<span>world</span>
</div>
<script>
(function(){
document.location =
'data:text/attachment;,' + //here is the trick
document.getElementById('hello').innerHTML;
//document.documentElement.innerHTML; //To Download Entire Html Source
})();
</script>
</body>
</html>
Edit after shesek comment
To add to Mic's terrific answer above, some additional points:
If you have Unicode content (Or want to preserve indentation in the source), you need to convert the string to Base64 and tell the Data URI to treat the data as such:
(function(){
document.location =
'data:text/attachment;base64,' + // Notice the new "base64" bit!
utf8_to_b64(document.getElementById('hello').innerHTML);
//utf8_to_b64(document.documentElement.innerHTML); //To Download Entire Html Source
})();
function utf8_to_b64( str ) {
return window.btoa(unescape(encodeURIComponent( str )));
}
utf_to_b64() via MDN -- works in Chrome/FF.
You can drop this all into an anchor tag, allowing you to set the download attribute:
<a onclick="$(this).attr('href', 'data:text/plain;base64,' + utf8_to_b64($('html').clone().find('#generate').remove().end()[0].outerHTML));" download="index.html" id="generate">Generate static</a>
This will download the current page's HTML as index.html and removes the link used to generate the output. This assumes the utf8_to_b64() function from above is defined somewhere else.
Some useful links on Data URIs:
MDN article
MSDN article
Depending on the size and if support is needed for ancient browsers, but you can consider creating a dynamic file using data: URIs and link to it. I'be seen several places that do that. To get the brorwser to download rather than display it, play around with the content type you put in the URI and use the new html5 download attribute. (Sorry for any typos, I'm writing from my phone)
I don't think you're going to be able to do it exactly the way you want to. JavaScript can't create a file and download it for security reasons. Nor can it create it on the server for download.
What I would do if I were you is, on the server side, create an output file with the session ID in the name in a temp directory as you create the output for the web page, and have a button on the web page with a link to that file.
You'll probably want a separate process to remove files over a day old or something like that.
Can you not cache the query results, and store it by some key? That way you can reference the same report output forever, or until your file garbage collector comes along. This also implies that you can create static URLs to report outputs, which tends to be nice.

Categories