Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable YouTube links with JavaScript?

I'm working on a tampermonkey script that lets you edit text on youtube just by clicking the text. I'd also like to edit the suggested videos on YouTube, but to do that, I need to disable the links temporarily. linkElement.onclick = function(e){return false;}; works for most links, but for some reason, it doesn't work on YouTube links. Would somebody know why this doesn't work?

Example of it working usually:

<a id='testlink' href='http://stackoverflow.com'>Test link</a>
<br />
<button onclick='document.getElementById("testlink").onclick=function(e){return false;};'>Disable link</button>

Like I said, this doesn't work on YouTube, and I don't know what code they use for their links. I think it has something to do with how it always seems to be one seamless page.

like image 346
Coarse Avatar asked May 04 '26 04:05

Coarse


1 Answers

Your best bet is probably to add a global (i.e. on the window object) event listener with useCapture and then to use event.stopImmediatePropagation().

Example, to block all clicks on anchor elements:

window.addEventListener('click', function(event) {
  var currentEl = event.target;
  while (currentEl && currentEl.tagName !== 'A') currentEl = currentEl.parentNode; 
  if (!currentEl) return;
  event.preventDefault();
  event.stopImmediatePropagation();
}, true); // true is for `useCapture`

However this won't be enough, since youtube has its own loading method for switching pages without doing actual page refreshes or having to click on actual anchors.

Thus you can generalize this method to prevent click event handling for almost all elements except the ones you are controlling:

function isAllowed(el) {
  // custom logic. e.g. block everything
  return false;
}

window.addEventListener('click', function(event) {
  if (isAllowed(event.target)) return;
  event.preventDefault();
  event.stopImmediatePropagation();
}, true);
like image 111
Maluen Avatar answered May 05 '26 19:05

Maluen