This repository has been archived by the owner on Aug 29, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcheck-if-bot.js
94 lines (82 loc) · 2.06 KB
/
check-if-bot.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/**
* Worker logic
* Checks if user agent is a bot or crawler, and if so, returns a simple string
* If you are not a bot, you see a complete web page
*
* @async
* @function
* @param {Request} request - The incoming request data
* @returns {Response} - Returns markup and headers
*/
async function handleRequest(request) {
const IS_BOT = checkIfBot(request.headers.get("user-agent"));
if (IS_BOT) {
return new Response("Sorry bot! No can do!");
}
const DATA = {
headers: {
...request.headers,
"Content-Type": "text/html;charset=UTF-8"
}
};
return new Response(bodyMarkup, DATA);
}
addEventListener("fetch", event => {
return event.respondWith(handleRequest(event.request));
});
/**
* @function
* @param {string} userAgent - Incoming user agent string
* @returns {boolean} - Returns whether the user agent is a bot or not
*/
function checkIfBot(userAgent) {
if (!userAgent)
throw new Error("No 'userAgent' parameter passed to checkIfBot()!");
if (userAgent) {
console.log("checkIfBot userAgent:", userAgent);
const botUserAgents = [
"Baiduspider",
"bingbot",
"Embedly",
"facebookexternalhit",
"LinkedInBot",
"outbrain",
"pinterest",
"quora link preview",
"rogerbot",
"showyoubot",
"Slackbot",
"TelegramBot",
"Twitterbot",
"vkShare",
"W3C_Validator",
"WhatsApp"
];
let containsBotKeyword = botUserAgents.find(element => {
const substr = new RegExp(`${element}`);
return substr.test(userAgent.toLowerCase());
});
if (containsBotKeyword !== undefined) {
containsBotKeyword = true;
} else if (containsBotKeyword === undefined) {
containsBotKeyword = false;
}
console.log("containsBotKeyword:", containsBotKeyword);
return containsBotKeyword;
}
}
const bodyMarkup = `
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Demo to check if you are a bot</title>
</head>
<body>
<main>
<article>
<h1>Demo to check if you are a bot</h1>
</article>
</main>
</body>
</html>
`;