문제

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?

도움이 되었습니까?

해결책

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);

다른 팁

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"} )
    }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top