在Greasemonkey脚本中未定义innerText

innerText is undefined in Greasemonkey script

本文关键字:未定义 innerText 脚本 Greasemonkey      更新时间:2023-09-26

我已经编写了代码来查询匹配字符串的文档,并从获得的字符串中生成URL。它通过标记元素查找匹配项,生成URL字符串,然后将链接附加到指定的parentNode对象。这段代码在纯javascript中工作得很好,但是当我把它放在Greasemonkey中时就会崩溃。我不知道为什么。

当我把它放在chrome控制台时,这是一个完整的工作版本:

//loop  through elements by classname and find string matches
regexQueryEmail = "(AccountEmailAddress''s)(.+?)(''n)"
regexQueryContact = "(Contact with ID: )(.+?)(''D)"
var Tags = document.getElementsByClassName('msg-body-div')
for (i = 0; i < Tags.length; i++) {
    matchEmail = Tags[i].innerText.match(regexQueryEmail)
    matchContact = Tags[i].innerText.match(regexQueryContact)
    if (matchEmail != null) {
        var emailString = matchEmail[2]
        var placeHolder = Tags[i]
    }
    if (matchContact != null) {
        var idString = matchContact[2]
    }
}
var urlFirst = "https://cscentral.foo.com/gp/stores/www.foo.com/gp/communications/manager/main/191- 4559276-8054240?ie=UTF8&customerEmailAddress="
var urlSecond = "%3E&initialCommId="
var cscURL = urlFirst + emailString + urlSecond + idString
var cscLink = document.createElement('a')
cscLink.innerText = 'Communication History'
cscLink.href = cscURL
placeHolder.parentNode.appendChild(cscLink)

当我把它粘在Greasemonkey,它给了我这个错误从Greasemonkey"编辑"屏幕:

/*
    Exception: Tags[i].innerText is undefined
    @Scratchpad:18
*/

它也告诉我,"占位符"是未定义的,但我现在无法复制这个。我有一种感觉,这与变量的作用域有关。我添加了"var Tags;"answers"var placeHolder;"到脚本的顶部,但它没有帮助。

Firefox使用element.textContent属性。

https://developer.mozilla.org/en-US/docs/Web/API/Node.textContent?redirectlocale=en-US& redirectslug = DOM % 2 fnode.textcontent

变量placeholder从未在您尝试使用它的作用域中声明过。相反,它在for循环的某个地方声明。请确保在同一作用域中声明它。

var Tags = document.getElementsByClassName('msg-body-div')
var placeholder; // declare in same scope
for (var i = 0; i < Tags.length; i++) {
    // lookup the tag once
    var tag = Tags[i];
    // get the text only once
    var text = tag.textContent;
    matchEmail = text.match(regexQueryEmail)
    matchContact = text.match(regexQueryContact)
    if (matchEmail != null) {
        var emailString = matchEmail[2]
        placeHolder = tag // deleted var statement
    }
    if (matchContact != null) {
        var idString = matchContact[2]
    }
}
...
// now you can use it.
if (placeHolder) {
    placeHolder.parentNode.appendChild(cscLink);
}