How I Disabled Every Link on a Webpage (Even Google) with JavaScript ๐
Recently, I challenged myself with a fun little task:
Disable every clickable link on a webpage, whether it's a local project page or a live site like Google's search results.
๐ฏ The Goal:
Prevent users from clicking on links, so no redirection or navigation happens.
๐ก Why do this?
- For testing UI behavior without navigation.
- For creating static demos or mockups.
- For temporarily disabling parts of a UI.
- Or... just to enjoy a technical challenge ๐
๐ ๏ธ First Approach (Basic)
I started with a simple approach:
js
document.querySelectorAll('a').forEach(link => {
link.addEventListener('click', function(event) {
event.preventDefault();
event.stopPropagation();
});
});
This prevents normal redirection from <a href="..."> tags.
โ
It works well... on simple websites.
But...
๐ง The Problem: It Doesnโt Work on All Sites
On complex websites like Google or Bing:
Links are created dynamically with JavaScript,
Events are handled at higher DOM levels (body, document, etc.),
And preventDefault() isnโt always enough ๐ฎ
โ
The Real Fix: pointerEvents
The magic CSS property:
link.style.pointerEvents = "none";
๐ This makes the element unclickable, unhoverable, and unfocusable via mouse.
Hereโs my working version:
const links = document.querySelectorAll('[role="tab"]'); // or 'a', depending on your target
links.forEach(link => {
link.addEventListener('click', function(event) {
event.preventDefault();
event.stopPropagation();
});
link.style.pointerEvents = "none"; // ๐ฅ blocks all mouse interaction
});
๐ง What I Learned
preventDefault() is useful, but not always sufficient.
pointerEvents = "none" is the most reliable way to block interaction.
Sites like Google use advanced DOM scripting โ you need to outsmart them ๐
Writing and testing scripts directly in the browser console is extremely powerful.
๐ Try It Yourself!
Need to disable links for a test, UI demo, or fun hack?
Try this in your browserโs dev console and adapt it as needed.
If you enjoyed this or found it helpful, follow me on Twitter or GitHub โ I share JavaScript tips and dev projects regularly.
Top comments (0)