greasemonkey脚本中未定义innerText

时间:2013-05-24 18:46:28

标签: javascript greasemonkey scope

我已经创建了代码来查询文档以匹配字符串,并从获得的字符串中创建一个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
*/

它还告诉我“placeHolder”未定义,但我现在无法复制它。我觉得它与变量的范围有关。我添加了“var Tags;”和“var placeHolder;”到脚本的顶部,它没有帮助。

1 个答案:

答案 0 :(得分:1)

Firefox使用element.textContent属性。

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

变量placeholder从未在您尝试使用它的范围内声明。而是在for循环中的某处声明了它。确保在同一范围内声明它。

E.g。

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);
}