在动态插入javascript到页面时如何防止"操作不安全"警告?

fre*_*ent 1 javascript security jquery dynamic

我正在尝试动态地将一个元,链接和脚本块添加到jQuery Mobile页面.

该脚本包含一条规则,我通过javascript添加到CSS样式表(不幸的是必须像这样).

看起来像这样:

<script type="text/javascript"
if ('addRule' in sheet) {
sheet.addRule(".splash:before",
  "background: url("' + x + '") no-repeat center center fixed; " +
  "-webkit-background-size: 100%; -moz-background-size: 100%; " +
  "-o-background-size: 100%; background-size: 100%; " +
  "-webkit-background-size: cover; -moz-background-size: cover;" +
  "-o-background-size: cover; background-size: cover;", 0);
} else if ('insertRule' in sheet) {
sheet.insertRule(".splash:before { " +
  "background: url("' + x + '") no-repeat center center fixed; " +
  "-webkit-background-size: 100%; -moz-background-size: 100%; " +
  "-o-background-size: 100%; background-size: 100%; " +
  "-webkit-background-size: cover; -moz-background-size: cover; "+
  "-o-background-size: cover; background-size: cover;" + " }", 0); 
}
</script>
Run Code Online (Sandbox Code Playgroud)

x作为背景图像URL,它可以动态地设置,当码块被附加到页头.

问题是:
我得到了这个:

SecurityError: The operation is insecure. [Break On This Error]     
slice.call( docElem.childNodes, 0 )[0].nodeType;
Run Code Online (Sandbox Code Playgroud)

在Firebug中报道.

如果我对x的URL进行硬编码它可以正常工作,所以我假设浏览器抱怨正在使用的URL变量.

问题:有什么
想法绕过这个吗?我需要动态传递URL.

小智 5

这几乎总是与同源政策有关的问题.这意味着您正在加载的文件(背景图像,javascript文件,css文件等)必须是相同的域,相同的子域,相同的协议(http vs https)和相同的端口.

另外,您是在本地还是在服务器上运行?在本地运行时,您将遇到这些问题,因为源在技术上是" file:/// ",因此如果您提供指向服务器上托管的文件的链接,您可能会收到这些错误.