我可以得到一个解释,为什么这不起作用吗?

huangapple go评论94阅读模式
英文:

Can i please get an explanation to why this is not working

问题

我正在开发一个 Chrome 扩展(仅供娱乐),并尝试使用内容脚本将脚本注入网页,但一直遇到问题。我想了解这两种方法是否有区别。

这个不起作用。我遇到了以下错误:
>Uncaught TypeError: Cannot read properties of undefined (reading '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)

我是否有什么不明白的地方?根据我的了解,这两种方法应该是一样的吗?

英文:

I am working on a chrome extension (for fun) and i am trying to use a content script to inject a script into the web page, but this keeps tripping me up. I would like to understand if there is a difference here.

This doesn't work. I am getting this error:
>Uncaught TypeError: Cannot read properties of undefined (reading 'appendChild')

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

Meanwhile on the contrary, this works:

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)

Is there something i don't understand, by my knowledge this should be the same thing?

答案1

得分: 3

使用括号来封装条件检查 head || documentElement 导致编译器认为你试图调用 onload 函数并链式调用 appendChild 函数。返回的错误是正确的,因为 onload 不返回值。

基本上,它会像这样读取你的代码:

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

如果在函数声明之后添加一个分号,那么它将正常工作。

希望这有所帮助!

英文:

The use of the parenthesis to encapsulate your conditional check for head || documentElement is causing the compiler to think you are trying to call the onload function and chain call appendChild from the result. The error that's coming back is correct because onload doesn't return a value.

Basically it's reading your code like this:

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

If you add a semicolon after the function declaration, then it'll work just fine.

Hope this helps!

huangapple
  • 本文由 发表于 2023年8月9日 09:37:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/76864045-2.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定