Search code examples
javascriptgoogle-chromebookmarklet

Bookmarklet returning Uncaught TypeError: Cannot read property 'click' of null


I'm completely new at coding and I'm attempting to create a bookmarklet that will automatically click checkboxes with certain names. In this case, I'm trying to get the bookmarklet to autoclick the "A" checkbox.

I'm using this website to test out my code. http://jsfiddle.net/fjaeger/L9z9t04p/4/

What I have saved in the bookmarklet is:

javascript:(function()%7Bdocument.querySelector('%23check-a').click()%7D)()

This is what I got after putting

 document.getElementById('check-a').click();

through https://mrcoles.com/bookmarklet/

My code runs fine when entering into the Chrome console but when I use it as a bookmark, it comes as

Uncaught TypeError: Cannot read property 'click' of null
at < anonymous>:1:47
at < anonymous>:1:57

Solution

  • The code you've written is correct. The problem here is the jsfiddle website. This site is running your code inside an iframe element, not on the page itself. document refers to the current document, but the iframe is a different document, and your code doesn't find the element.

    You could try with

    window.frames[0].document.getElementById('check-a').click();
    

    However, you'll get an error, because that frame is on a different origin and the browser is blocking access to cross-origin resources.

    Try to write a simple HTML page to test your bookmarklet.