英文:
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!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论