我可以给你解释一下为什么这个不起作用。

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

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.html
匿名

发表评论

匿名网友

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

确定