Google loading behavior: strange change depending on whether the script contains an alert()

17 views
Skip to first unread message

Joe D

unread,
May 11, 2016, 5:58:58 AM5/11/16
to greasemonkey-users
I am having a hard time understanding why a script is running correctly when a debugging alert() statement is present, but no longer functions when I remove it.

Below, I have reduced the problem to its essence. On Google searches, the script attempts to insert "Hey there!" just above the search results (div id sprvd).

This works perfectly when I run a search from the Firefox search bar (which passes the query parameters via GET). But when I run the search by first opening Google.com, and post the query in the search box, the Hey there! is not displayed... Unless I uncomment the alert() line, which confirms that the script is running, then correctly shows the results preceded by Hey there!
(Even when Hey there! does not display, Firebug confirms that the sprvd div is present.)

Why does adding an alert() cause the script to work? Does it have something to do with giving more time to the page to load completely? If so how can I do the same without an alert?

Would be much grateful for any insights!

// ==UserScript==
// @name        Google Test
// @namespace   google_test
// @description Google Test
// @include     http*://www.google.*/*
// @include     http*://www.google.*?*
// @version     0.1
// @grant     none
// ==/UserScript==

(function() {
 
 
//  alert('running')
 
var start_of_results = /(?=<div id="sprvd")/;
  document
.body.innerHTML= document.body.innerHTML.replace(start_of_results,
   
'hey there' + '$&' );

})();



Joe D

unread,
May 11, 2016, 6:14:21 AM5/11/16
to greasemonkey-users
I may have answered my own question by letting the page finish to load.
For anyone on the same track, I used this answer on stack:

window.addEventListener('load', function() {
   
// your code here
}, false);


Reply all
Reply to author
Forward
0 new messages