Code works in console/scratchpad but not in a Greasemonkey script? [duplicate]

╄→гoц情女王★ 提交于 2019-12-01 12:51:04

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

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"} )
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!