场景描述:
当使用web组件加载带有iframe的页面时,由于H5的iframe标签的几个限制条件,可能会出现以下问题:
1.由于iframe也要遵守浏览器同源策略,也有对应的白名单限制,所以也会出现跨域或者无法加载的问题,大多出现在本地或沙箱中的H5资源内联iframe时,并且cookie有时候也设置不上
2.在应用侧调用runJavascript方法调用不到iframe里面,且主frame和iframe无法相互调用对方的属性
场景一:iframe加载问题
--在线的url里面嵌套的iframe基本上没有加载问题以及cookie设置问题
--本地的文件嵌套在线的iframe由于同源策略或者网页frame-ancestors属性的白名单限制会出现加载问题,即:
当控制台报错Refused to frame 'https://......com/' because an ancestor violates the following Content Security Policy directive: "frame-ancestors *........com",可能是frame-ancestors 指令导致的,这个指令用于指定哪个域名的网页可以嵌入当前页面,如果当前页面的主frame不在允许的源列表中,浏览器将拒绝加载该页面。
在一个本地的H5嵌入这个链接进行测试,可复现这个问题。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Set Cookie in Iframe</title>
</head>
<body>
<iframe id="myIframe"
src="https://developer.huawei.com/consumer/cn/?ha_linker=eyJ0cyI6MTcwODEyOTY4MDk5MywiaWQiOiI5NGE4Y2U3YzZkNWFjMzI1M2VlOWRkNjBhMWNhYjMwZCJ9"
style="width: 100%; height: 400px;"></iframe>
<button id="setCookieButton">主frame</button>
</body>
</html>
解决方案就是通过拦截替换请求,将在源列表中允许的域名给到本地H5上即可规避这个问题,以下示例就是将主域名换做.huawei.com,这样即可成功加载。
import web_webview from '@ohos.web.webview';
import { url } from '@kit.ArkTS';
@Entry
@Component
struct SecondPage {
@State message: string = 'Hello World';
webviewController: web_webview.WebviewController = new web_webview.WebviewController();
@State url: string | Resource = 'https://xxx.html';
responseData: WebResourceResponse = new WebResourceResponse()
dir = getContext().filesDir;
aboutToAppear(): void {
web_webview.WebviewController.setWebDebuggingAccess(true)
}
build() {
Column() {
Web({ src: this.url, controller: this.webviewController })
.domStorageAccess(true)
.fileAccess(true)
.onInterceptRequest((event) => {
if (!event || !event.request) {
return null
}
let request: WebResourceRequest = event.request
let requestUrl: string = request.getRequestUrl()
if (requestUrl.startsWith('https://developer1.huawei.com/')) {
let relativePath: string = url.URL.parseURL(requestUrl).pathname.replace(/^\//, '');
const resource = $rawfile(relativePath);
this.responseData = new WebResourceResponse();
this.responseData.setResponseData(resource);
let mimeType = "text/plain";
if (relativePath.endsWith(".html")) {
mimeType = "text/html";
} else if (relativePath.endsWith(".css")) {
mimeType = "text/css";
} else if (relativePath.endsWith(".js")) {
mimeType = "text/javascript";
}
if (mimeType.length > 0) {
this.responseData.setResponseEncoding('utf-8');
this.responseData.setResponseMimeType(mimeType);
this.responseData.setResponseCode(200);
this.responseData.setReasonMessage('OK');
this.responseData.setResponseIsReady(true)
}
return this.responseData;
}
return null
})
}
.padding({ top: 28 })
.height('100%')
.width('100%')
}
}
--本地的文件嵌套本地的iframe一般不会有加载问题,但会出现cookie设置不上的问题
web组件的规格是目前只能给http或https协议的url设置cookie,所以放在本地rawfile和沙箱里的离线资源直接加载是无法设置cookie的,目前有两种方案:
- 通过拦截替换请求,给本地resource协议的iframe替换为http或https协议,然后直接使用configCookieSync设置即可;
- 可以使用js接口来给iframe设置cookie,也需使用拦截替换的方案:
具体的思路就是通过document.getElementById}获取元素并添加事件监听器,然后当点击事件点击后通过.contentWindow.document.cookie方法给iframe设置上cookie;注意:这个代码中是以两个本地H5文件来进行演示的,由于本地的H5都是以resource协议来加载的,根据浏览器内核的限制,是无法设置上cookie的,所以需要使用此方案。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Set Cookie in Iframe</title>
</head>
<body>
<iframe id="myIframe" src="./rich.html" style="width: 100%; height: 400px;"></iframe>
<button id="setCookieButton">设置 cookie</button>
<script>
document.getElementById('setCookieButton').addEventListener('click', function() {
var iframe = document.getElementById('myIframe');
// 确保 iframe 已经加载完成
if (iframe.contentWindow.document.readyState === 'complete') {
// 设置 cookie
iframe.contentWindow.document.cookie = "username=JohnDoe; path=/";
console.info("Cookie 已设置");
} else {
iframe.onload = function() {
// 设置 cookie
iframe.contentWindow.document.cookie = "username=JohnDoe; path=/";
console.info("Cookie 已设置");
};
}
});
</script>
</body>
</html>
场景二:主frame和iframe间通信
--通过contentWindow进行通信
具体的示例可以参考上文的js接口来给iframe设置cookie,注:此方法只能在同源的主frame和子frame中使用,这样主frame才能访问子frame的内部dom
--通过Window.postMessage()进行通信
它的原理就是一个窗口可以引用另一个窗口的一些属性,然后在窗口上调用 targetWindow.postMessage() 方法分发一个 MessageEvent 消息 ,这个方法不受同源策略的限制,但是必须是http或https协议的域名下才行,所以还是得使用上面的拦截替换的方案
可以参考以下代码,这个代码是调用runJavaScript方法的时候作用不到iframe里面,使用postMessage进行消息通信。
import webview from '@ohos.web.webview';
import { url } from '@kit.ArkTS';
@Entry
@Component
struct Index {
controller: webview.WebviewController = new webview.WebviewController();
@State url: string | Resource = 'https://developer1.huawei.com/postMessage.html';
responseData: WebResourceResponse = new WebResourceResponse()
dir = getContext().filesDir;
aboutToAppear(): void {
webview.WebviewController.setWebDebuggingAccess(true)
}
build() {
Column() {
Web({
src: this.url,
controller: this.controller
})
.domStorageAccess(true)
.fileAccess(true)
.onPageEnd(()=>{
this.controller.runJavaScript('callIframeFunction()')
})
.onInterceptRequest((event) => {
if (!event || !event.request) {
return null
}
let request: WebResourceRequest = event.request
let requestUrl: string = request.getRequestUrl()
if (requestUrl.startsWith('https://developer1.huawei.com/')) {
let relativePath: string = url.URL.parseURL(requestUrl).pathname.replace(/^\//, '');
const resource = $rawfile(relativePath);
this.responseData = new WebResourceResponse();
this.responseData.setResponseData(resource);
let mimeType = "text/plain";
if (relativePath.endsWith(".html")) {
mimeType = "text/html";
} else if (relativePath.endsWith(".css")) {
mimeType = "text/css";
} else if (relativePath.endsWith(".js")) {
mimeType = "text/javascript";
}
if (mimeType.length > 0) {
this.responseData.setResponseEncoding('utf-8');
this.responseData.setResponseMimeType(mimeType);
this.responseData.setResponseCode(200);
this.responseData.setReasonMessage('OK');
this.responseData.setResponseIsReady(true)
}
return this.responseData;
}
return null
})
}
}
}
以下H5中的主frame中的代码,在callIframeFunction方法里监听来自iframe的消息以及发送消息到iframe。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Parent Page</title>
</head>
<body>
<iframe id="myIframe" src="./jsb1.html" width="600" height="400"></iframe>
<button onclick="callIframeFunction()">Call iframe function</button>
<script type="text/javascript">
function callIframeFunction() {
var iframe = document.getElementById('myIframe');
// 监听来自 iframe 的消息
window.addEventListener('message', function(event) {
// 处理来自 iframe 的消息
console.log('Result from iframe:', event.data);
});
// 发送消息到 iframe
iframe.contentWindow.postMessage({ action: 'test', value: 'aaa' }, 'https://developer1.huawei.com/jsb1.html');
}
</script>
</body>
</html>
以下是iframe的代码,用于接受来自主frame的消息并回消息给到它。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Iframe Page</title>
<script>
// 示例的函数,在 iframe 内部定义
function test(value) {
return 'Received ' + value;
}
// 监听来自父页面的消息
window.addEventListener('message', function(event) {
// 不做同源检查,直接处理消息
if (event.data.action === 'test') {
var result = test(event.data.value);
// 将结果发送回父页面
event.source.postMessage(result, event.origin);
}
});
</script>
</head>
<body>
<h1>Iframe Page</h1>
<p>这里是嵌入的 iframe 页面。</p>
</body>
</html>
FAQ
Q:web的三个拦截回调对iframe的拦截情况是什么样的?
--onLoadIntercept和onInterceptRequest都可以拦截到主frame和iframe的url,onOverrideUrlLoading回调只能拦截到页面内的跳转,写在web组件src属性里的链接和loadUrl都不会触发此回调,并且只能拦截到resource协议,file协议或自定义协议的iframe,http/https协议的iframe拦截不到。且当onOverrideUrlLoading返回true后,主frame可以加载,http/https协议的iframe可以加载,所有的本地iframe都无法加载
Q:H5上面动态加载多个iframe,为什么历史栈变多了?
--iframe里加载的也是一个html页面,有完整的上下文,当有多个iframe需要在主页面加载完成后再加载时,就相当于跳转了几次页面,历史栈就会增加,这个是目前的规格。onInterceptRequest无法控制iframe里的src是否可以加载,可以通过onLoadIntercept和onOverrideUrlLoading回调拦截iframe里的src,根据业务逻辑设置是否允许加载来解决历史栈增加的问题。注:onOverrideUrlLoading方法无法拦截http/https协议的iframe,请按需选择使用哪个回调
Q:能否通过onPageBegin或者onPageEnd监听iframe的加载情况?
--不行,目前onPageBegin和onPageEnd回调只会在主frame触发。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。