1

I'm trying to write a script to make the map larger on Google Flights.

I've got the jQuery working in the Firefox scratchpad. This script does exactly what I am trying to accomplish:

$('div').filter(function(){ 
   return $(this).css('width') == '648px'
}).css({"width":"900px","height":"550px"});

but when I paste that into a Greasemonkey script, it doesn't work. If I add some console.logs to debug, I can verify that the script is running and the filter is working correctly, but it's not modifying the CSS. Any ideas?

Brock Adams
  • 90,639
  • 22
  • 233
  • 295
spazzed
  • 93
  • 2
  • 9

2 Answers2

4

Sometime you will need to make sure the script is executed after that the page was loaded

$(function(){
   // YOUR CODE HERE
});

You can also try with setTimeout and put 2sec (2000)

var myfunc = function(){
  // YOUR CODE HERE
};
setTimeout(myfunc, 2000);
Yves Lange
  • 3,914
  • 3
  • 21
  • 33
  • This worked great, thanks! My function was loading and running before the map was initialized, even though the document was ready. – spazzed Jan 31 '14 at 16:30
  • 3
    Often times, waiting for a fixed interval will not give repeatable, reliable results (unless you set the delay to a very large, annoying value). There are techniques and [the `waitForKeyElements` utility](http://stackoverflow.com/a/11197969/331508) for this kind of thing. – Brock Adams Jan 31 '14 at 18:54
0

Content added by AJAX-driven pages is often added long after your userscript runs, so the script does not normally see it.

You can use a long, fixed, interval as shown in Kursion's answer, but that has drawbacks:

  1. Choosing the delay value is problematic. And if the page is slow to load for the usual reasons, a fixed delay is likely to be inadequate.
  2. Making a longer delay will still not always work and slows/stops your userscript for annoyingly long periods.
  3. An very dynamic pages, a setTimeout will only catch the first instance, at best. Subsequent nodes will be missed.

A better way is to either use MutationObservers or a utility like waitForKeyElements().
Both have advantages and disadvantages, but I've found waitForKeyElements to be simpler and more robust in general. (Disclosure: I wrote it.)

Here is a complete userscript showing the question code factored to work on dynamic web pages:

// ==UserScript==
// @name     _Fix div CSS on AJAX-driven pages
// @match    http://YOUR_SERVER.COM/YOUR_PATH/*
// @require  http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
// @require  https://gist.github.com/raw/2625891/waitForKeyElements.js
// @grant    GM_addStyle
// ==/UserScript==
//- The @grant directive is needed to restore the proper sandbox.

waitForKeyElements ("div", adjustSelectDivdimensions);

function adjustSelectDivdimensions (jNode) {
    if (jNode.css('width') == '648px') {
        jNode.css( {"width": "900px", "height": "550px"} )
    }
}
Community
  • 1
  • 1
Brock Adams
  • 90,639
  • 22
  • 233
  • 295