Chrome 我可以请得到一个解释,为什么这是不工作[重复]

4jb9z9bj  于 12个月前  发布在  Go
关注(0)|答案(1)|浏览(60)

这个问题已经有答案了

JavaScript - why does inclusion of parenthesis result in an error in ternary expression?(1个答案)
上个月关门了。
我正在开发一个Chrome扩展(为了好玩),我试图使用一个内容脚本将一个脚本注入到网页中,但这一直让我绊倒。我想知道这里是否有区别。
这不管用我收到这个错误:
未捕获的类型错误:无法读取undefined的属性(阅读“appendChild”)

var injectableScript = document.createElement("script")
injectableScript.src = chrome.runtime.getURL("requestwatch.js")
injectableScript.onload = function () {
    injectableScript.remove()
}
(document.head || document.documentElement).appendChild(injectableScript)

与此同时,相反,这起作用:

var injectableScript = document.createElement("script")
injectableScript.src = chrome.runtime.getURL("requestwatch.js")
injectableScript.onload = function () {
    injectableScript.remove()
}
var targetElement = document.head || document.documentElement;
targetElement.appendChild(injectableScript)

是不是有什么我不明白的,据我所知,这应该是同一件事?

cgvd09ve

cgvd09ve1#

使用括号封装head || documentElement的条件检查会导致编译器认为您正在尝试调用onload函数,并从结果中链调用appendChild。返回的错误是正确的,因为onload doesn't return a value
基本上,它是这样阅读代码的:

injectibleScript.onload = function() {
 ...
}(...).appendChild(...)

如果你在函数声明后加一个分号,那么它就能正常工作。
希望这对你有帮助!

相关问题