Javascript 使用javascript从Web应用程序强制在移动Safari中打开链接
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7930001/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Force link to open in mobile safari from a web app with javascript
提问by Aron Woost
When calling window.open()
in a iOS web app, the page opens in the web app instead of mobile safari.
window.open()
在 iOS Web 应用程序中调用时,页面会在 Web 应用程序中打开,而不是在移动 safari 中打开。
How can I force the webpage to open in mobile safari?
如何强制网页在 mobile safari 中打开?
Note: Using straight <a href>
links is not an option.
注意:使用直线<a href>
链接不是一种选择。
回答by Samuli Hakoniemi
This is possible. Tested with iOS5 stand-alone web app:
这个有可能。使用 iOS5 独立 Web 应用程序测试:
HTML:
HTML:
<div id="foz" data-href="http://www.google.fi">Google</div>
JavaScript:
JavaScript:
document.getElementById("foz").addEventListener("click", function(evt) {
var a = document.createElement('a');
a.setAttribute("href", this.getAttribute("data-href"));
a.setAttribute("target", "_blank");
var dispatch = document.createEvent("HTMLEvents");
dispatch.initEvent("click", true, true);
a.dispatchEvent(dispatch);
}, false);
Can be tested here: http://www.hakoniemi.net/labs/linkkitesti.html
回答by Aron Woost
Turns out it is NOT POSSIBLEto escape the iOS web app with a JavaScript window.open()
. If you want a link to open in mobile safari you have to use <a href>
links.
原来它是不是可能的逃跑与一个JavaScript iOS的Web应用程序window.open()
。如果您想在移动 Safari 中打开链接,则必须使用<a href>
链接。
回答by Roman Rhrn Nesterov
Vue implementation. Hope will helpful.
Vue 实现。希望会有所帮助。
<template>
<div @click='handler()'>{{ text }}</div>
</template>
<script>
export default {
props: {
href: String,
text: String,
},
methods: {
handler() {
const a = document.createElement('a')
a.setAttribute('href', this.href)
a.dispatchEvent(new MouseEvent("click", {'view': window, 'bubbles': true, 'cancelable': true}))
}
}
}
</script>
回答by Gary Vernon Grubb
You can force iOS to open a link from PWA in safari using window.open() provided you either use a different sub-domain or use http instead of https.
您可以使用 window.open() 强制 iOS 在 safari 中打开来自 PWA 的链接,前提是您使用不同的子域或使用 http 而不是 https。
For example for take example.com
例如以example.com为例
window.open('http://example.com','_blank')
Note: My server will redirect http to https once opened in the browser. So there is no security concern.
注意:在浏览器中打开后,我的服务器会将 http 重定向到 https。所以没有安全问题。
(or)
(或者)
window.open('api.example.com','_blank')