I'm trying to write a simple userscript which does something with the textarea in twitter.
When using the debug console in Chrome, "document.getElementsByTagName('textarea')" returns an array containing the textbox (where you type the tweet), but in my userscript it just returns an empty array. Is there something very basic and wrong that I am doing here? I've tried it both with and without the "@run-at document-end", but with both I can't get at the textarea.
Thanks for reading!
// ==UserScript==
// @name twitter-edit
// @namespace foo
// @description twitter
// @match http://www.twitter.com/*
// @match https://www.twitter.com/*
// @match https://twitter.com/*
// @match http://twitter.com/*
// @run-at document-end
// ==/UserScript==
(function() {
var textareas = document.getElementsByTagName('textarea');
window.alert('textareas len ' + textareas.length); // <-- **THIS SOMEHOW RETURNS 0**
if (textareas.length != 1) {
window.alert('error');
} else {
var tweetbox = textareas[0];
window.alert('tweetbox: ' + tweetbox);
}
}());
Because that site is so infested with ajax, and because it dives into at least 1 iFrame, you must wait a bit before your script can see that textbox.
Also, when following links on Twitter, the page is often just changed by AJAX methods. In that case normal scripts won't fire.
To compensate, just set a timer that continually checks for that twitter box, and will catch new boxes, as the page is "reloaded" by ajax.
This script works:
// ==UserScript==
// @name twitter-edit
// @namespace foo
// @description twitter
// @match http://www.twitter.com/*
// @match https://www.twitter.com/*
// @match https://twitter.com/*
// @match http://twitter.com/*
// @run-at document-end
// ==/UserScript==
//--- 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!');
}
}
}