Chrome本地跨域请求设置,实现HTML模板页

按照需求,公司现在需要通过第三方的API反馈的数据,进行在本地就可以打开的静态页面程序(完全脱离IIS等服务器)。为了更好的维护项目,需要实现静态HTML引入HTML模板,完成ASP.NET模板页的类似功能。HTML本身并不具备该功能,只能借助于JS。因此想到了使用AngularJS的ng-include或者jQuery的load。但是完成如下测试代码后,Chrome浏览器,提示“Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.”。而火狐则可以正常使用(IE和国产浏览器由于本人不使用,因此未做测试)。

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $("#header").load("header.html");
            $("#footer").load("footer.html");
        });

    </script>
</head>
<body>
    <div>
        <h2>jQuery load 加载方式</h2>
        <div id="header"></div>
        <div id="context">页面内容体</div>
        <div id="footer"></div>
    </div>
    <div ng-app="">
        <h2>AngularJS ng-include 指令</h2>
        <ng-include src="'header.html'"></ng-include>
        <div ng-include="'footer.html'"></div>
    </div>

</body>
</html>

 

导致该错误的原因,主要是Chrome自身的安全机制,只需要在Chrome的快捷方式中配置一下即可解决该问题。通过关键词Google"配置Chrome支持本地(File协议)AJAX请求"可以找不少相关的解决方案。

Webkit内核的浏览器安全策略决定了File协议访问的应用无法使用XMLHttpRequest对象,错误消息已经明确的指出了:

Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
(跨域请求仅支持协议:http, data, chrome, chrome-extension, https.)

在Chrome的快捷方式中选择属性,在“目标”中按照下图的方式进行配置,“ --allow-file-access-from-files”(复制双引号间的文字,注意最前边有一个空格)。“确定”保存后,关闭Chrome浏览器然后再次打开后,该问题就解决了(一定要重新关闭后,否则设置不会生效,刷新页面该问题并没有得到解决)。

搞定后可以正常执行:

 

posted @ 2018-03-16 12:07  [FRL]...MoNey  阅读(511)  评论(0编辑  收藏  举报