Cordova iOS中如何将子index.html页面加载至localhost
Cordova iOS WKWebKit 子页面改为localhost协议加载解决方案
针对你使用Cordova 11、Cordova iOS 6.2开发时,主页面已通过config.xml配置为localhost加载,但子页面www/world/wikitude_AR/index.html仍以file协议加载的问题,提供以下几种可行方案:
方案1:使用相对路径跳转(推荐,符合SPA模式)
主页面已处于app://localhost/index.html环境,直接通过相对路径跳转子页面,会自动继承localhost协议:
- JS跳转示例:
window.location.href = './world/wikitude_AR/index.html'; - 标签跳转示例:
跳转后子页面地址为<a href="./world/wikitude_AR/index.html">进入AR页面</a>app://localhost/world/wikitude_AR/index.html,不再使用file协议。
方案2:配置allow-navigation确保路径权限
在config.xml的iOS平台节点内添加导航规则,允许应用内导航到localhost下的所有路径,避免协议切换:
<platform name="ios"> <preference name="scheme" value="app" /> <preference name="hostname" value="localhost" /> <!-- 添加以下规则 --> <allow-navigation href="app://localhost/*" /> </platform>
该配置确保所有指向app://localhost下的页面都能正常加载,不会 fallback 到file协议。
方案3:文件路径转localhost URL(原生触发加载场景)
如果是通过原生代码或文件API获取子页面路径,可使用cordova-plugin-file将本地文件路径转换为localhost格式:
document.addEventListener("deviceready", function() { window.resolveLocalFileSystemURL( cordova.file.applicationDirectory + "www/world/wikitude_AR/index.html", function(entry) { // 替换file协议为app://localhost var targetUrl = entry.toURL().replace('file:///', 'app://localhost/'); window.location.href = targetUrl; }, function(error) { console.error("获取文件路径失败:", error); } ); }, false);
验证方法
跳转后通过Chrome开发者工具查看页面地址,确认协议为app://localhost开头即配置生效。
内容的提问来源于stack exchange,提问作者heojung
相关产品推荐
相关产品推荐

