Wicky
Wicky

Reputation: 13

Want to make Google-search page automatically show more definitions by setting attribute "aria-expanded" to "true" on page load

I always want to see the expanded section when searching for a definition, so I would like it to automatically expand upon loading the page.

Using Tampermonkey to create a userscript that applies to google.com/search?q=meaning+*

From inspecting page elements I have found line <div class="S8ee5 CwbYXd wHYlTd vk_arc" aria-controls="tsuid_46" aria-expanded="false" data-fbevent="fastbutton" role="button" tabindex="0">

"aria-expanded" changes value when clicking on the button.

Class "S8ee5 CwbYXd wHYlTd vk_arc" has spaces in it, which apparently means multiple classes, so should setAttribute() access by index?

I added window.onload to try to make it run after the page has finished loading in case it tries to access elements prematurely.

My ineffective attempt:

(window.onload = function() {
    'use strict';

    document.getElementsByClassName("S8ee5 CwbYXd wHYlTd vk_arc")[0].setAttribute("aria-expanded", "true");
})();

Upvotes: 0

Views: 70

Answers (1)

cssyphus
cssyphus

Reputation: 40038

Here, this should do the trick.

Note that I am using the old-tech setTimeout() instead of doing this properly with a MutationObserver. I haven't used MutationObserver enough to be able to do this quickly and a cursory initial attempt was not successful within the time available, so here is the Quick 'n Dirty setTimeout solution:

Note that you might need to increase the _TIMEDELAY value (milliseconds) if it is not reliably dropping-down the extra info.

// ==UserScript==
// @name         Google Dictionary auto-expand
// @namespace    http://cssyphus.com
// @version      0.2
// @match        https://www.google.com/search?q=meaning+*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=google.com
// @grant        none
// ==/UserScript==

(async function() {
    'use strict';
    const _TIMEDELAY = 500;
    const $ = document.querySelector.bind(document);
    let csh = 0;

    while (csh < 500){
        await sleep(100);
        csh = getComputedStyle( $('#kp-wp-tab-overview > div') );
        if ( csh.getPropertyValue('height').replace('px','') > 400 ){
            break;
        }
    }
    await sleep(_TIMEDELAY);
    $('#kp-wp-tab-overview hr+div').click();

})();
function sleep(ms){
    return new Promise(function (resolve, reject) {
        setTimeout(()=>{
            resolve();
        },ms);
    })
}

Upvotes: 0

Related Questions