有没有办法用React检测IE浏览器,或者重定向到某个页面,或者给出任何有用的消息.我在JavaScript中找到了一些东西,但不确定如何将其用于React+TypeScript.
var isEdge = !isIE && !!window.StyleMedia;
有没有办法用React检测IE浏览器,或者重定向到某个页面,或者给出任何有用的消息.我在JavaScript中找到了一些东西,但不确定如何将其用于React+TypeScript.
var isEdge = !isIE && !!window.StyleMedia;
你已经走上了正确的道路,你可以使用这些来有条件地呈现jsx或帮助路由...
我已经成功地使用了以下方法.
最初是-How to detect Safari, Chrome, IE, Firefox and Opera browser?
// Opera 8.0+
const isOpera = (!!window.opr && !!opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
// Firefox 1.0+
const isFirefox = typeof InstallTrigger !== 'undefined';
// Safari 3.0+ "[object HTMLElementConstructor]"
const isSafari = /constructor/i.test(window.HTMLElement) || (function (p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window['safari'] || (typeof safari !== 'undefined' && safari.pushNotification));
// Internet Explorer 6-11
const isIE = /*@cc_on!@*/false || !!document.documentMode;
// Edge 20+
const isEdge = !isIE && !!window.StyleMedia;
// Chrome 1 - 71
const isChrome = !!window.chrome && (!!window.chrome.webstore || !!window.chrome.runtime);
// Blink engine detection
const isBlink = (isChrome || isOpera) && !!window.CSS;
请注意,由于浏览器更改,它们都有可能被弃用.
我用它们来做如下react :
content(props){
if(!isChrome){
return (
<Otherjsxelements/>
)
}
else {
return (
<Chromejsxelements/>
)
}
}
然后在我的主组件中调用{this.Content()}来呈现不同的浏览器特定元素.
伪代码可能看起来像这样...(未经测试):
import React from 'react';
const isChrome = !!window.chrome && (!!window.chrome.webstore || !!window.chrome.runtime);
export default class Test extends React.Component {
content(){
if(isChrome){
return (
<div>Chrome</div>
)
} else {
return (
<div>Not Chrome</div>
)
}
}
render() {
return (
<div>Content to be seen on all browsers</div>
{this.content()}
)
}
}