-1

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)

1 Answers1

0

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'))
yuriy636
  • 11,171
  • 5
  • 37
  • 42
  • I'm a little confused how I would implement this into what I have... I can't seem to get it to work. – SoaringGecko Mar 15 '20 at 15:27
  • This will return a filtered array, which you can access the same way as your current code `[Math.floor(Math.random()*document.links.length)]`. Can you edit your question with the updated approach? – yuriy636 Mar 15 '20 at 15:49