Reputation: 39
I tried to write a Greasemonkey userscript that checks to see if the user is in one of a list of websites.
If the user is indeed in one of them, the script will alert:
Enough with this domain already!
The purpose of the script is to remind the user that he stop visiting this site (addiction-like behavior).
The output should include only the domain, without the TLD.
I have tried the following code which failed (the code runs on a collection of tlds and uses the collection to strip these away):
let sites = ['walla.com', 'mako.co.il'];
let tlds = new RegExp('\.+(com|co.il)');
for (let i = 0; i < sites.length; i++) {
if (window.location.href.indexOf(sites[i]) != -1 ) {
sites.forEach((e)=>{
e.replace(tlds, '').split('.').pop(),
});
alert(` Enough with this ${sites[i]} already! `);
}
}
No console errors.
To reproduce, install the script in Greasemoneky/Tampermonkey and try it in the listed sites.
Upvotes: 0
Views: 62
Reputation: 192287
You should iterate the sites, and if the href contains the site (sites[i]
), replace everything after the domain (the don onward), alert, and break the loop:
const sites = ['walla.com', 'mako.co.il'];
const regex = /\..+/;
const href = 'http://www.mako.co.il/news?partner=NavBar'; // this replace window.location.href for demo purposes
for (let i = 0; i < sites.length; i++) {
if (href.includes(sites[i])) { // if the href includes the sites[i]
const domain = sites[i].replace(regex, ''); // remove the 1st dot and everything after it to get the domain name
alert(` Enough with this ${domain} already! `);
break; // or return if in a function
}
}
Upvotes: 1