简体   繁体   中英

Opening new tab with url in react

I am trying to make a function to open a new tab with item.url . The problem is, the item.url property is given by client, not by me. So I cannot ensure if it starts with https:// or http:// . For example, user can give google.com instead of https://google.com .

Below is my code. (This component is on /example )

<URLText onClick={() => window.open(item.url, '_blank')}>Click</URLText>
  • URLText is just a styled component(div).

  • If item.url is google.com , it opens a new tab with url localhost:3000/example/google.com ,
    instead of opening just google.com .

Try this way.

<URLText onClick={() => window.open('//'+item.url, '_blank')}>Click</URLText>

Sample fiddle - https://jsfiddle.net/pecu0szq/12/

Use this instead:

<URLText onClick={() => window.open((item.url.startsWith("http://") || item.url.startsWith("https://")) ? item.url : "http://" + item.url, '_blank')}>Click</URLText>

This uses the ternary operator to check if the passed URL contains https:// or http:// , appends it to the beginning of the URL if it doesn't, and returns the appended or original value to the function parameter.

You can use window.location.protocol to get the protocol of current 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM