• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# 解决Web组件本地资源跨域问题
2
3## 拦截本地资源跨域
4为了提高安全性,ArkWeb内核不允许file协议或者resource协议访问URL上下文中来自跨域的请求。因此,在使用Web组件加载本地离线资源的时候,Web组件会拦截file协议和resource协议的跨域访问。当Web组件无法访问本地跨域资源时,开发者可以在devtools控制台中看到类似以下报错信息:
5
6```
7Access to script at 'xxx' from origin 'xxx' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, arkweb, data, chrome-extension, chrome, https, chrome-untrusted.
8```
9
10## 本地资源跨域问题解决方法
11如果Web组件要成功访问这些跨域资源,开发者需要使用http或者https等协议替代原本使用的file协议或者resource协议进行加载。其中替代的url的域名为自己构造的仅供个人或者组织使用的域名,尽量不要和网络上真实存在的域名冲突。同时需要开发者使用Web组件的[onInterceptRequest](../reference/apis-arkweb/ts-basic-components-web.md#oninterceptrequest9)对本地资源进行拦截替换。
12
13以下结合示例说明如何解决本地资源跨域访问失败的问题。其中index.htmljs/script.js置于工程中rawfile目录下。如果使用resource协议访问index.htmljs/script.js将被跨域拦截无法加载。示例中使用https:\//www\.example.com/域名替换原本的resource协议,同时使用[onInterceptRequest](../reference/apis-arkweb/ts-basic-components-web.md#oninterceptrequest9)接口替换资源,使得js/script.js可以成功加载,解决了跨域拦截的问题。
14
15```ts
16// main/ets/pages/index.ets
17import web_webview from '@ohos.web.webview'
18
19@Entry
20@Component
21struct Index {
22  @State message: string = 'Hello World';
23  webviewController: web_webview.WebviewController = new web_webview.WebviewController();
24  // 构造域名和本地文件的映射表
25  schemeMap = new Map([
26    ["https://www.example.com/index.html", "index.html"],
27    ["https://www.example.com/js/script.js", "js/script.js"],
28  ])
29  // 构造本地文件和构造返回的格式mimeType
30  mimeTypeMap = new Map([
31    ["index.html", 'text/html'],
32    ["js/script.js", "text/javascript"]
33  ])
34
35  build() {
36    Row() {
37      Column() {
38        // 针对本地index.html,使用http或者https协议代替file协议或者resource协议,并且构造一个属于自己的域名。
39        // 本例中构造www.example.com为例。
40        Web({ src: "https://www.example.com/index.html", controller: this.webviewController })
41          .javaScriptAccess(true)
42          .fileAccess(true)
43          .domStorageAccess(true)
44          .geolocationAccess(true)
45          .width("100%")
46          .height("100%")
47          .onInterceptRequest((event) => {
48            if (!event) {
49              return;
50            }
51            // 此处匹配自己想要加载的本地离线资源,进行资源拦截替换,绕过跨域
52            if (this.schemeMap.has(event.request.getRequestUrl())) {
53              let rawfileName: string = this.schemeMap.get(event.request.getRequestUrl())!;
54              let mimeType = this.mimeTypeMap.get(rawfileName);
55              if (typeof mimeType === 'string') {
56                let response = new WebResourceResponse();
57                // 构造响应数据,如果本地文件在rawfile下,可以通过如下方式设置
58                response.setResponseData($rawfile(rawfileName));
59                response.setResponseEncoding('utf-8');
60                response.setResponseMimeType(mimeType);
61                response.setResponseCode(200);
62                response.setReasonMessage('OK');
63                response.setResponseIsReady(true);
64                return response;
65              }
66            }
67            return null;
68          })
69      }
70      .width('100%')
71    }
72    .height('100%')
73  }
74}
75
76```
77
78```html
79<!-- main/resources/rawfile/index.html -->
80<html>
81<head>
82	<meta name="viewport" content="width=device-width,initial-scale=1">
83</head>
84<body>
85<script crossorigin src="./js/script.js"></script>
86</body>
87</html>
88```
89
90```js
91// main/resources/rawfile/js/script.js
92const body = document.body;
93const element = document.createElement('div');
94element.textContent = 'success';
95body.appendChild(element);
96```