Javascript 如何以编程方式清空浏览器缓存?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8155064/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to programmatically empty browser cache?
提问by Tower
I am looking for a way to programmatically empty the browser cache. I am doing this because the application caches confidential data and I'd like to remove those when you press "log out". This would happen either via server or JavaScript. Of course, using the software on foreign/public computer is still discouraged as there are more dangers like key loggers that you just can't defeat on software level.
我正在寻找一种以编程方式清空浏览器缓存的方法。我这样做是因为应用程序缓存了机密数据,我想在您按“注销”时删除这些数据。这将通过服务器或 JavaScript 发生。当然,仍然不鼓励在外国/公共计算机上使用该软件,因为有更多的危险,例如您无法在软件级别上击败的键盘记录器。
采纳答案by Zeal Murapa
It's possible, you can simply use jQuery to substitute the 'meta tag' that references the cache status with an event handler / button, and then refresh, easy,
有可能,您可以简单地使用 jQuery 替换引用缓存状态的“元标记”与事件处理程序/按钮,然后刷新,简单,
$('.button').click(function() {
$.ajax({
url: "",
context: document.body,
success: function(s,x){
$('html[manifest=saveappoffline.appcache]').attr('content', '');
$(this).html(s);
}
});
});
NOTE: This solution relies on the Application Cache that is implemented as part of the HTML 5 spec. It also requires server configuration to set up the App Cache manifest. It does not describe a method by which one can clear the 'traditional' browser cache via client- or server-side code, which is nigh impossible to do.
注意:此解决方案依赖于作为 HTML 5 规范的一部分实现的应用程序缓存。它还需要服务器配置来设置应用程序缓存清单。它没有描述一种可以通过客户端或服务器端代码清除“传统”浏览器缓存的方法,这几乎是不可能做到的。
回答by NullUserException
There's no waya browser will let you clear its cache. It would be a huge security issue if that were possible. This could be very easily abused - the minute a browser supports such a "feature" will be the minute I uninstall it from my computer.
有没有办法浏览器会让你清除缓存。如果可能的话,这将是一个巨大的安全问题。这很容易被滥用 - 浏览器支持这种“功能”的那一刻就是我从计算机上卸载它的那一刻。
What you cando is to tell it not to cache your page, by sending the appropriate headers or using these meta tags:
您可以做的是通过发送适当的标头或使用这些元标记来告诉它不要缓存您的页面:
<meta http-equiv='cache-control' content='no-cache'>
<meta http-equiv='expires' content='0'>
<meta http-equiv='pragma' content='no-cache'>
You might also want to consider turning off auto-complete on form fields, although I'm afraid there's a standard way to do it (see this question).
您可能还想考虑关闭表单字段的自动完成功能,尽管我担心有一种标准的方法可以做到这一点(请参阅此问题)。
Regardless, I would like to point out that if you are working with sensitive data you should be using SSL. If you aren't using SSL, anyone with access to the network can sniff network traffic and easily see what your user is seeing.
无论如何,我想指出的是,如果您正在处理敏感数据,则应该使用 SSL。如果您不使用 SSL,任何有权访问网络的人都可以嗅探网络流量并轻松查看您的用户所看到的内容。
Using SSL also makes some browsers notuse caching unless explicitly told to. See this question.
除非明确告知,否则使用 SSL 还会使某些浏览器不使用缓存。看到这个问题。
回答by Joish
use html itself.There is one trick that can be used.The trick is to append a parameter/string to the file name in the script tag and change it when you file changes.
使用 html 本身。有一个技巧可以使用。技巧是将参数/字符串附加到脚本标记中的文件名,并在文件更改时更改它。
<script src="myfile.js?version=1.0.0"></script>
<script src="myfile.js?version=1.0.0"></script>
The browser interprets the whole string as the file path even though what comes after the "?" are parameters. So wat happens now is that next time when you update your file just change the number in the script tag on your website (Example <script src="myfile.js?version=1.0.1"></script>) and each users browser will see the file has changed and grab a new copy.
浏览器将整个字符串解释为文件路径,即使在“?”之后是什么。是参数。所以现在发生的是,下次更新文件时,只需更改网站上脚本标记中的数字(示例<script src="myfile.js?version=1.0.1"></script>),每个用户浏览器都会看到文件已更改并获取新副本。
回答by Admiral Duck
The best idea is to make js file generation with name + some hash with version, if you do need to clear cache, just generate new files with new hash, this will trigger browser to load new files
最好的办法是使用名称+一些带有版本的哈希生成js文件,如果您确实需要清除缓存,只需使用新的哈希生成新文件,这将触发浏览器加载新文件
回答by rajagopalx
Initially I tried various programmatic approach in my html, JS to clear browser cache. Nothing works on latest Chrome.
最初我在我的 html、JS 中尝试了各种编程方法来清除浏览器缓存。在最新的 Chrome 上没有任何效果。
Finally, I ended up with .htaccess:
最后,我得到了 .htaccess:
<IfModule mod_headers.c>
Header set Cache-Control "no-cache, no-store, must-revalidate"
Header set Pragma "no-cache"
Header set Expires 0
</IfModule>
Tested in Chrome, Firefox, Opera
在 Chrome、Firefox、Opera 中测试
Reference: https://wp-mix.com/disable-caching-htaccess/
回答by Jay Shah
location.reload(true); will hard reload the current page, ignoring the cache.
Cache.delete()can also be used for new chrome, firefox and opera.
location.reload(true); 将硬重新加载当前页面,忽略缓存。
Cache.delete()也可用于新的 chrome、firefox 和 opera。
回答by kakhkAtion
On Chrome, you should be able to do this using the benchmarking extension. You need to start your chrome with the following switches:
在 Chrome 上,您应该能够使用基准测试扩展来执行此操作。您需要使用以下开关启动 chrome:
./chrome --enable-benchmarking --enable-net-benchmarking
In Chrome's console now you can do the following:
现在在 Chrome 的控制台中,您可以执行以下操作:
chrome.benchmarking.clearCache();
chrome.benchmarking.clearHostResolverCache();
chrome.benchmarking.clearPredictorCache();
chrome.benchmarking.closeConnections();
As you can tell from above commands, it not only clears the browser cache, but also clears the DNS cache and closes network connections. These are great when you're doing page load time benchmarking. Obviously you don't have to use them all if not needed (e.g. clearCache() should suffice if you need to clear the cache only and don't care about DNS cache and connections).
从上面的命令可以看出,它不仅会清除浏览器缓存,还会清除 DNS 缓存并关闭网络连接。当您进行页面加载时间基准测试时,这些非常有用。显然,如果不需要,您不必全部使用它们(例如,如果您只需要清除缓存而不关心 DNS 缓存和连接,则 clearCache() 就足够了)。
回答by haimirick
//The code below should be put in the "js" folder with the name "clear-browser-cache.js"
(function () {
var process_scripts = false;
var rep = /.*\?.*/,
links = document.getElementsByTagName('link'),
scripts = document.getElementsByTagName('script');
var value = document.getElementsByName('clear-browser-cache');
for (var i = 0; i < value.length; i++) {
var val = value[i],
outerHTML = val.outerHTML;
var check = /.*value="true".*/;
if (check.test(outerHTML)) {
process_scripts = true;
}
}
for (var i = 0; i < links.length; i++) {
var link = links[i],
href = link.href;
if (rep.test(href)) {
link.href = href + '&' + Date.now();
}
else {
link.href = href + '?' + Date.now();
}
}
if (process_scripts) {
for (var i = 0; i < scripts.length; i++) {
var script = scripts[i],
src = script.src;
if (src !== "") {
if (rep.test(src)) {
script.src = src + '&' + Date.now();
}
else {
script.src = src + '?' + Date.now();
}
}
}
}
})();
At the end of the tah head, place the line at the code below
< script name="clear-browser-cache" src='js/clear-browser-cache.js' value="true" >< /script >
回答by r.delic
You can now use Cache.delete()
您现在可以使用Cache.delete()
Example:
例子:
let id = "your-cache-id";
// you can find the id by going to
// application>storage>cache storage
// (minus the page url at the end)
// in your chrome developer console
caches.open(id)
.then(cache => cache.keys()
.then(keys => {
for (let key of keys) {
cache.delete(key)
}
}));
Works on Chrome 40+, Firefox 39+, Opera 27+ and Edge.
适用于 Chrome 40+、Firefox 39+、Opera 27+ 和 Edge。
回答by caramba
Imagine the .jsfiles are placed in /my-site/some/path/ui/js/myfile.js
想象一下.js文件被放置在/my-site/some/path/ui/js/myfile.js
So normally the script tag would look like:
所以通常脚本标签看起来像:
<script src="/my-site/some/path/ui/js/myfile.js"></script>
Now change that to:
现在将其更改为:
<script src="/my-site/some/path/ui-1111111111/js/myfile.js"></script>
Now of course that will not work. To make it work you need to add one or a few lines to your .htaccessThe important line is: (entire .htaccess at the bottom)
现在这当然行不通。要使其工作,您需要在您.htaccess的重要行中添加一行或几行:(底部的整个 .htaccess)
RewriteRule ^my-site\/(.*)\/ui\-([0-9]+)\/(.*) my-site//ui/ [L]
So what this does is, it kind of removes the 1111111111from the path and links to the correct path.
因此,它的作用是1111111111从路径中删除并链接到正确的路径。
So now if you make changes you just have to change the number 1111111111to whatever number you want. And however you include your files you can set that number via a timestamp when the js-file has last been modified. So cache will work normally if the number does not change. If it changes it will serve the new file (YES ALWAYS) because the browser get's a complete new URL and just believes that file is so new he must go get it.
所以现在如果您进行更改,您只需将数字更改为1111111111您想要的任何数字。但是,您可以包含您的文件,您可以通过上次修改 js 文件时的时间戳设置该数字。因此,如果数字不变,缓存将正常工作。如果它发生变化,它将提供新文件(始终是),因为浏览器获取的是一个完整的新 URL,并且认为该文件是如此新,他必须去获取它。
You can use this for CSS, faviconsand what ever gets cached. For CSS just use like so
您可以将其用于CSS,favicons以及缓存的内容。对于 CSS 就这样使用
<link href="http://my-domain.com/my-site/some/path/ui-1492513798/css/page.css" type="text/css" rel="stylesheet">
And it will work! Simple to update, simple to maintain.
它会起作用!更新简单,维护简单。
The promised full .htaccess
承诺的完整 .htaccess
If you have no .htaccess yet this is the minimum you need to have there:
如果您还没有 .htaccess,这是您需要的最低限度:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^my-site\/(.*)\/ui\-([0-9]+)\/(.*) my-site//ui/ [L]
</IfModule>

