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