Reputation: 103
Massive irony here is I started writing this script as an answer to another question on the StackExchange network.
I'm writing a Greasemonkey Script which I want to run on Google search results. Whenever a user searches for something I wish the script to run the command.
document.querySelector(".lr_dct_spkr > input:nth-child(1)").click();
Autplays the audio when you query "define x" into Google
However I realised quickly that simply writing this into the bottom of the script means it only gets triggered when search results load for the first time, and I need it to trigger every time a new query (or set of search results appear). I initially thought this may be an Ajax problem and tried to solve it using a waitForKeyElement function but I cannot seem to trigger it no matter what kind of element I wait for (The best element to wait for would be the cards that that the definitions appear on, but it doesn't really matter what element).
// @include www.google.com/*
// @require https://git.io/vMmuf
// @version 1
// @grant none
// ==/UserScript==
$.waitForKeyElements ("div.lr_dct_ent_ph",launchsound);
function launchsound(){
document.querySelector(".lr_dct_spkr > input:nth-child(1)").click();
}
I then worked out that Google doesn't even use Ajax, but this solution should work anyway?
TL:DR: How do I write a script that triggers every time a new search query is put into google instant?
Upvotes: 0
Views: 264
Reputation: 3189
Parse URL to find out if a search query has been responded to, i.e. are you on the results page.
// ==UserScript==
// @name My Userscript
// @include https://www.google.com/search?*
// @require https://cdnjs.cloudflare.com/ajax/libs/URI.js/1.18.10/URI.min.js
// @grant GM_setValue
// @grant GM_getValue
// ==/UserScript==
(function() {
'use strict';
var currentSearch = URI.parseQuery(window.location.search).q;
var lastSearch = GM_getValue('lastSearch');
if (currentSearch != lastSearch) {
GM_setValue('lastSearch', currentSearch);
console.log('Do Whatever You Want HERE');
}
})();
Upvotes: 1