如何防止“;操作不安全”;在页面中动态插入javascript时发出警告

how to prevent "operation is insecure" warning when dynamically inserting javascript into a page?

本文关键字:javascript 插入 动态 警告 操作 何防止 不安全      更新时间:2023-09-26

我正在尝试向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>

x是背景图像url,当代码块被附加到页头时可以动态设置。

问题是:
我得到这个:

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

在Firebug中报告。

如果我为x硬编码一个URL,它可以正常工作,所以我假设浏览器会抱怨使用了URL变量。

问题:
你知道如何规避吗?我需要动态地传入URL。

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

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

我也遇到了同样的问题,只有当你用sessionStorage方法在本地打开文件时才会发生,所以在wamp等web服务器上运行它。