Reputation: 4014
I have the following snippet of code to be executed by Tampermonkey in chrome on the website http://www.thefreedictionary.com/abnormally
I tried it standalone in the page and it works but it does not work through Tampermonkey.
The code is as follows:
// ==UserScript==
// @name linkify span href
// @namespace http://use.i.E.your.homepage/
// @version 0.1
// @description enter something useful
// @match http://www.thefreedictionary.com/*
// @require http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js
// @copyright 2012+, You
// @grant GM_log
// ==/UserScript==
//alert("hello");
jQuery(document).ready (Greasemonkey_main);
function Greasemonkey_main ()
{
alert("hjello");
jQuery("span.hvr").each(function () { jQuery(this).wrap('<a href="/' + jQuery(this).text() + '" style="text-decoration:none;color:inherit" target="_blank"></a>')})
}
To check I also put an alert, the alert works, but not the jquery one line of code .
No clue why . please help .
Note :
What this one line code does ?
It just wraps every span tag in the page with an anchor tag .
How to try out that code in that page ?
add the script tag of jQuery link and then execute that one line from console and it will work .
Upvotes: 0
Views: 1649
Reputation: 47913
The problem is that the span.hvr
links are generated dynamically: when the page loads, they do not exist, but then a script generates them sometime later.
So for your script to work, it should wait for span.hvr
elements to be present first, before doing anything further.
The following modified script should work:
// ==UserScript==
// @name linkify span href
// @namespace http://use.i.E.your.homepage/
// @version 0.1
// @description enter something useful
// @match http://www.thefreedictionary.com/*
// @require http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js
// @copyright 2012+, You
// @grant GM_log
// ==/UserScript==
//alert("hello");
jQuery(document).ready(Greasemonkey_main);
function Greasemonkey_main ()
{
var isReady = jQuery("span.hvr").length > 0;
if (!isReady) {
setTimeout(Greasemonkey_main, 500);
return;
}
jQuery("span.hvr").each(function () {
jQuery(this).wrap('<a href="/' + jQuery(this).text() + '" style="text-decoration:none;color:inherit" target="_blank"></a>')
});
}
If there are pages in which it is possible to have no span.hvr
elements, then you should make the script a bit smarter – stop retrying after 5-10 seconds for example.
Upvotes: 3