如何用object标签在普通HTML中嵌入Angular站点?兼容IE11与FireFox
你遇到的问题其实很常见:object标签在Chrome能正常加载Angular SPA,但IE11和Firefox因为各自的渲染机制限制,无法正确解析SPA的路由和资源加载逻辑。下面给你几个可行的替代方案,既避开iframe,又能兼容目标浏览器:
方案1:IE专属iframe降级(最小改动)
既然你不想全局用iframe,但IE11对object加载外部HTML的支持确实有硬伤,可以用IE条件注释做针对性降级——只给IE11加载iframe,其他浏览器继续用object:
<!--[if IE 11]> <iframe src="http://localhost:4200/auth/user-details/step1" width="800px" height="600px" style="overflow:auto;border:5px ridge blue"></iframe> <![endif]--> <!--[if !IE]><!--> <object type="text/html" data="http://localhost:4200/auth/user-details/step1" width="800px" height="600px" style="overflow:auto;border:5px ridge blue"></object> <!--<![endif]-->
这个方案几乎不用改现有逻辑,只是给IE11做了兼容兜底,成本最低。
方案2:将Angular打包为Web Component(最原生的嵌入方式)
如果想彻底摆脱iframe/object的限制,可以把你的Angular页面打包成自定义元素(Web Component),这样就能像普通HTML标签一样直接嵌入宿主页面,完全没有隔离层问题:
步骤:
在Angular项目中启用自定义元素支持:
- 安装
@angular/elements依赖:npm install @angular/elements --save - 修改组件代码,把目标组件注册为自定义元素
- 打包时配置输出为自定义元素(具体配置可参考Angular官方文档的自定义元素章节)
- 安装
打包后会得到一个独立的JS文件,在宿主页面引入它:
<script src="path/to/your-angular-custom-element-bundle.js"></script>
- 直接在页面中使用自定义标签:
<auth-user-details-step1 style="width:800px;height:600px;overflow:auto;border:5px ridge blue"></auth-user-details-step1>
注意:IE11需要加载Web Component的polyfill(比如@webcomponents/webcomponentsjs)才能支持自定义元素,配置起来也很简单。
方案3:Embed标签+IE fallback(备选)
embed标签在部分浏览器中比object更稳定,但IE11对它的支持依然有限,可以搭配fallback使用:
<embed type="text/html" src="http://localhost:4200/auth/user-details/step1" width="800px" height="600px" style="overflow:auto;border:5px ridge blue" /> <!-- IE11 fallback --> <!--[if IE 11]> <object data="http://localhost:4200/auth/user-details/step1" width="800px" height="600px" style="overflow:auto;border:5px ridge blue"> <iframe src="http://localhost:4200/auth/user-details/step1" width="800px" height="600px" style="overflow:auto;border:5px ridge blue"></iframe> </object> <![endif]-->
不过这个方案的兼容性不如前两个,更适合临时过渡。
额外提醒:跨域问题
如果你的宿主页面和Angular站点不在同一个域名下,一定要在Angular后端配置CORS允许跨域访问,否则所有嵌入方式都会被Firefox、IE11等浏览器拦截,这是很多人忽略的关键点。
内容的提问来源于stack exchange,提问作者Akshaya Moorthy

