Search code examples
javascriptrandombookmarklet

restrict a bookmarklet that opens a random link on page


I found this bookmarklet that opens a random link on your current page.

javascript:void(window.open(document.links[Math.floor(Math.random()*document.links.length)].href,'_self'));

I wanted to use this on a website, but I also wanted to restrict it so certain links wouldn't be opened. Is there a way I can do this?

(also I found the bookmarklet here)


Solution

  • The main point that you are looking for is how to filter an array.

    You might notice that document.links.filter() throws an error, that's because it's not an array per se, but an HTMLCollection (it has no .filter() methods), so you have to convert it to an array first.

    I used the most modern way, your usage might differ:

    [...document.links]
      .filter(link => !link.href.includes('stackoverflow'))