用Javascript动态插入脚本 [英] Dynamically Inserting Script with Javascript

查看:109
本文介绍了用Javascript动态插入脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

长话短说我正在研究Google Chrome扩展程序。这些扩展在默认情况下无法访问他们正在操作的页面范围内的变量(您需要通过DOM进行通信)。



我是什么试图做的是在页面中插入一个脚本;这可以通过定义脚本标记和src属性来正常工作。



问题是这个脚本需要事先初始化一个变量。为了初始化这个变量,我试图用内联代码构建一个脚本元素(而不是从外部源代码加载),但是我无法使它工作。

这是否可能,如果是这样,我如何在脚本中定义源代码?我已经尝试将包含JS源代码的文本节点附加到脚本元素中,但无济于事。 解决方案

但做到这一点的最佳方式可能是通过将数据注入DOM来传达数据: http://code.google.com/chrome/extensions/content_scripts.html#host-page-communication



您也是可以通过执行以下操作来完成此操作:

  var script = document.createElement('script'); 
script.type ='text / javascript';
script.text ='alert(It works!);';
document.head.appendChild(script);

我没有测试过这个,但我猜测它可以从您的内容脚本中运行。 / p>

Long story short I'm working on a Google Chrome Extension. The extensions don't have access to variables in the scope of the page they are operating on by default (you need to communicate through the DOM).

What I'm trying to do is insert a script into the page; this works fine by defining a script tag and a src attribute.

The problem is this script needs a variable to be initialized beforehand. In order to initialize this variable I'm trying to construct a script element with its code inline (rather than loaded from an external source) but I'm having trouble getting it to work.

Is this possible and if so, how do I define the source inside the script? I've tried appending a text-node containing the JS source to the script element but to no avail.

解决方案

It sucks, but the best way to do this is probably to communicate your data by injecting it into the DOM: http://code.google.com/chrome/extensions/content_scripts.html#host-page-communication

You also might be able to accomplish this by doing something like:

var script = document.createElement('script');
script.type = 'text/javascript';
script.text = 'alert("It works!");';
document.head.appendChild(script);

I haven't tested this, but I'm guessing it will work from your content scripts.

这篇关于用Javascript动态插入脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆