如何给script标签增加可执行的javascript代码
动态创建的script标签,如何设置innerHTML为javascript代码,使脚本运行起来,而不是通过加载js文件来实现脚本的动态运行。
动态创建script标签并运行javascript代码,可以借鉴jquery框架的代码,经过提取后源代码如下
<script> var rnotwhite = /\S/; var scriptEval = false; var root = document.documentElement, script = document.createElement("script"), div = document.createElement("div"), id = "script" + new Date().getTime(); script.type = "text/javascript"; try { script.appendChild(document.createTextNode("window." + id + "=1;")); } catch (e) { } root.insertBefore(script, root.firstChild); // Make sure that the execution of code works by injecting a script // tag with appendChild/createTextNode // (IE doesn't support this, fails, and uses .text instead) if (window[id]) { scriptEval = true; delete window[id]; } // Evalulates a script in a global context function globalEval(data) { if (data && rnotwhite.test(data)) { // Inspired by code by Andrea Giammarchi // http://webreflection.blogspot.com/2007/08/global-scope-evaluation-and-dom.html var head = document.getElementsByTagName("head")[0] || document.documentElement, script = document.createElement("script"); script.type = "text/javascript"; if (scriptEval) { script.appendChild(document.createTextNode(data)); } else { script.text = data; } // Use insertBefore instead of appendChild to circumvent an IE6 bug. // This arises when a base node is used (#2709). head.insertBefore(script, head.firstChild); head.removeChild(script); } } globalEval("alert('编程设计网')") </script>
加支付宝好友偷能量挖...
原创文章,转载请注明出处:如何给script标签增加可执行的javascript代码