Greasemonkey with jQuery, how to write the greasemonkey script to modify page DOM elements?

泪湿孤枕 提交于 2019-12-05 10:34:01

问题


From the greasemonkey wiki page, there is an example using jQuery with greasemonkey. The code is listed below and the location of the page is http://wiki.greasespot.net/Third-Party_Libraries#jQuery

// ==UserScript==
// @name          jQuery Example
// @require       http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js
// ==/UserScript==

// Append some text to the element with id someText using the jQuery library.
$("#someText").append(" more text.");

This example script modify the DOM directly. Do I need to surround the code with a jQuery function like this:

// ==UserScript==
// @name          jQuery Example
// @require       http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js
// ==/UserScript==

// Append some text to the element with id someText using the jQuery library.
jQuery(function(){
    $("#someText").append(" more text.");   
})

I ask this question is because my greasemonkey code is not executed every time the page is refreshed. Any ideas on this issue? Thanks.


回答1:


No, there is no point in wrapping your script code in a jQuery() call, nor in using $(document).ready ().

Greasemonkey automatically fires after both the DOMContentLoaded event (same as the jQuery wrapper or ready event), and after GM's version of jQuery is loaded.

Also note that that wiki page is outdated. GM works fine with jQuery 1.6.2 now.

You didn't show the relevant code, nor link to the target page, but the most-likely reasons the "Greasemonkey code is not executed every time the page is refreshed" are:

  1. There is an error in the GM script.

  2. The target content is loaded separately, via AJAX.
    You can use code in this pattern, to get around that:

    //--- This handles both page-load delays, and AJAX changes.
    setInterval (function() { checkForTweetbox (); }, 500);
    
    function checkForTweetbox () {
        var tweetbox = document.querySelector ('div.tweet-box textarea');
        if (tweetbox) {
            if (! tweetbox.weHaveProcessed) {
                tweetbox.weHaveProcessed    = true;
                alert ('New tweet-box found!');
            }
        }
    }
    


来源:https://stackoverflow.com/questions/7283923/greasemonkey-with-jquery-how-to-write-the-greasemonkey-script-to-modify-page-do

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