非常基本的Chrome用户标题问题 - 在DOM中找不到元素
-
25-10-2019 - |
题
我正在尝试编写一个简单的用户标记,该订阅在Twitter中使用Textarea进行操作。
在Chrome中使用Debug控制台时,“ document.getElementsbytagname('textarea')”返回包含文本框的数组(您在其中输入Tweet),但在我的Userscript中,它只是返回一个空数组。我在这里做什么非常基本和错误?我在有没有“@run-at document-end”的情况下尝试了它,但是两者都无法在Textarea上获得。
谢谢阅读!
// ==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);
}
}());
解决方案
因为该站点被Ajax如此侵扰,并且由于它至少介入1 iframe中,因此您必须等待一点,然后才能看到该文本框。
另外,在Twitter上遵循链接时,该页面通常只是通过AJAX方法更改。在这种情况下,普通脚本不会开火。
为了补偿,只需设置一个计时器,该计时器不断检查该Twitter框,并将捕获新的框,因为该页面是由Ajax“重新加载”的。
该脚本有效:
// ==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!');
}
}
}
其他提示
您确定脚本执行时已经存在文本方面吗?
我可以在Twitter上的DOM中找到TextArea,但在页面静态HTML代码中找不到,因此在页面充电后可能会加载它。在文本中,您的脚本应加载。
不隶属于 StackOverflow