Home > OS >  javascript: How to make all links on youtube to open in new tab
javascript: How to make all links on youtube to open in new tab

Time:10-11

Example I have this youtube link which shows search results

https://www.youtube.com/results?search_query=himalayas

I am using firefox and its developer tools

I am trying to run this js script to make left click any link on the page to open in a new tab

code1

var e = document.createElement("base");
e.target = "_blank";
document.head.appendChild(e); 

Code2

var links = document.links;
for (var i = 0; i < links.length; i  ) {
     links[i].target = "_blank";
}

Both of them add the target attribute

But after this script also i cannot open the link on new tab when left clicking

Any idea how can i do this

CodePudding user response:

You either have to

  1. remove the yt-simple-endpoint class that exists on the a href tags
    var links = document.links;
    for (var i = 0; i < links.length; i  ) {
         links[i].classList.remove('yt-simple-endpoint')
         links[i].target = "_blank";
    }

If you remove the class it affects the styling, but you can always fix that by re-adding the styles.

or

  1. remove the click event listener that's attached to <ytd-app>

I don't think it's easy to remove event listeners in Firefox. You might be able to using Firebug. Chrome has getEventListeners, so you can run

const ytdApp = document.getElementsByTagName('ytd-app')[0]
ytdApp.removeEventListener('click', getEventListeners(ytdApp).click[0].listener)

var links = document.links;
for (var i = 0; i < links.length; i  ) {
    links[i].classList.remove('yt-simple-endpoint')
    links[i].target = "_blank";
}
  • Related