javascript 将 js 注入头部(脚本中有完整代码)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13573290/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
inject js to head (with full-code in script)
提问by mmmh
I want to add a script to the head of a site so the the head of the target html looks like so <head><script type="text/javascript">*some code...*</script></head>
.
我想将脚本添加到站点的头部,以便目标 html 的头部看起来像这样<head><script type="text/javascript">*some code...*</script></head>
。
With this script works that perfect:
使用此脚本可以完美运行:
var head = document.getElementsByTagName('head')[0],
script = document.createElement('script');
script.src = 'http://www.example.com/example.js';
head.appendChild(script);
But i don't want to use any link in source.
但我不想在源代码中使用任何链接。
So i'm tried to add some code like this:
所以我试图添加一些这样的代码:
function addJS(jsCode) {
var styleElement = document.createElement('script');
styleElement.type = 'text/javascript';
(scriptElement.javascript) {
scriptElement.javascript.jsText = jsCode
scriptElement.appendChild(document.createTextNode(jsCode))
document.getElementsByTagName('head')[0].appendChild(scriptElement);
}
var jsCode = '';
jsCode += 'code';
jsCode += 'some more code';
But I've failed. That script is not working.
但我失败了。该脚本不起作用。
How can I add a Element to the head of any html site like this? Would be great if someone could help me.
如何将元素添加到任何这样的 html 站点的头部?如果有人可以帮助我,那就太好了。
回答by Bruno
回答by Eric Goncalves
Using jquery
使用jQuery
var head = document.getElementsByTagName('head')[0],
script = document.createElement('script');
$(script).attr('type' , 'text/javascript');
head.appendChild(script);
$(script).append("alert('Hello')");