Greasemonkey with jQuery, how to write the greasemonkey script to modify page DOM elements?
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 librar开发者_JS百科y.
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.
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:
There is an error in the GM script.
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!'); } } }
精彩评论