Search code examples
javascriptgoogle-chromegmailbookmarklet

How to make stable bookmarklet for Gmail


I made a simple bookmarklet just add "is:unread" in Gmail search bar.

javascript:
(function () {
    // add "is:unread" after the query
    // e.g. "from:kim-kardashian" -> "from:kim-kardashian is:unread"
    document.getElementsByClassName("gb_Df")[0].value = 
        document.getElementsByClassName("gb_Df")[0].value.concat("is:unread");
    // click search button
    document.getElementsByClassName("gb_Ef gb_Qf")[0].click();
    }
)();

It worked well yesterday, but It doesn't work today because of the className has changed. I assume the className of search bar is changed for each session. If this is true, is there an alternative way that adds is:unread at the end of the search query?


Solution

  • 3rd party resources outside of the your locus of control are generally never thought of as stable. This is why we have labeled versions (e.g., dev = always in flux) and contracts to try and approach stability.

    For something like this HTML is generally more stable than class names, but would never say this plugin is stable while the use case is unsupported by Google.

    So if indeed, what is stated is true, that the CSS class names change per session, could select from the DOM based on HTML structure or another attribute that is not hashed.


    Just took a look at gmail and indeed gb_Df class name is the search bar. Guess is your account has been automagically opted into a an AB test of one gmail version to another which has generated different class name hashes.

    In this scenario would choose placeholder. So something like:

    document.querySelector('[placeholder="Search mail"]')
    

    Based on experience (completely anecdotal), is very unlikely this value will change and there is currently one on the page. Could check other reasonably stable attributes to be sure you've the right one. Just keep in mind plugin hacks like this are unstable, can only incrementally increase stability by using more stable selectors, because the ground they rely on (Gmail DOM) is moving at the pace of Google. Good luck :)