Javascript 在react中打开url为的新选项卡
我正在尝试创建一个函数,用Javascript 在react中打开url为的新选项卡,javascript,reactjs,typescript,vanilla-typescript,Javascript,Reactjs,Typescript,Vanilla Typescript,我正在尝试创建一个函数,用item.url打开一个新选项卡。 问题是,item.url属性是由客户端提供的,而不是由我提供的。 所以我不能确定它是以https://还是http://开头。 例如,用户可以给google.com而不是https://google.com 下面是我的代码。(此组件位于/example上) window.open(item.url,'.\u blank')}>单击 URLText只是一个样式化组件(div) 如果item.url是google.com,它将打开一
item.url
打开一个新选项卡。
问题是,item.url
属性是由客户端提供的,而不是由我提供的。
所以我不能确定它是以https://还是http://开头。
例如,用户可以给google.com
而不是https://google.com
下面是我的代码。(此组件位于/example
上)
window.open(item.url,'.\u blank')}>单击
只是一个样式化组件(div)URLText
- 如果
是item.url
,它将打开一个新选项卡,其中urlgoogle.com
,localhost:3000/example/google.com
而不是只打开google.com
window.open((item.url.startsWith(“http://”)| | | item.url.startsWith(“https://”))?item.url:“http://“+item.url”,_blank')单击
这使用三元运算符检查传递的URL是否包含
https://
或http://
,如果不包含,则将其附加到URL的开头,并将附加值或原始值返回到函数参数。您可以使用window.location.protocol
获取当前URL的协议
function handleURL(url) {
if (url.includes("http://") || url.includes("https://")) {
return window.open(url, '_blank')
}
window.open(`${location.protocol}//${url}`, '_blank')
}
<URLText onClick={() => handleURL(item.url)}>Click</URLText>
函数handleURL(url){
if(url.includes(“http:/”)| | url.includes(“https:/”)){
返回窗口。打开(url“\u blank”)
}
window.open(`${location.protocol}/${url}`,'\u blank')
}
handleURL(item.url)}>单击
试试这种方法
<URLText onClick={() => window.open('//'+item.url, '_blank')}>Click</URLText>
window.open('/'+item.url'.\u blank')}>单击
示例fiddle-可以假设任何使用
https://
的网站都会将HTTP重定向到https吗?不,这不安全,我也不确定。我建议使用Zam Abdul Vahid的答案。
<URLText onClick={() => window.open('//'+item.url, '_blank')}>Click</URLText>