Coarse
Coarse

Reputation: 91

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.

Upvotes: 3

Views: 317

Answers (1)

Maluen
Maluen

Reputation: 1841

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);

Upvotes: 1

Related Questions