Using Twitter Web Intent in NextJs throws a "Cross-Origin-Opener-Policy" error message

78 Views Asked by At

I am trying to use Twitter Web Intent on NextJs. I previously use react-share library for the Twitter Share but I'm suddenly getting "Cross-Origin-Opener-Policy" error message when using SSO. Thanks again, I've been trying to solve this for a couple of days already. Please let me know if you need more details and I'd be happy to share some more. Tyyyy

So I tried using this method to manually trigger the web intent. But it also gives me the same error.

<a href="twitter_intent_url" rel="noopener noreferrer" target="_blank"> share </a>

...

I also tried the window.open option:

const twitterShareUrl = `https://twitter.com/intent/tweet?text=${encodeURIComponent(
    text
  )}&url=${encodeURIComponent(url)}`

const handleShareClick = () => {
    const windowOptions = 'width=550,height=350'
    // Open a new popup window with the Twitter intent URL
    window.open(twitterShareUrl, 'twitter-share', windowOptions)
}

//usage
<Button onClick={handleShareClick} colorScheme="twitter">
 Share with twitter
</Button>

...

another option i tried is creating an api proxy on the nextjs api


import { NextApiRequest, NextApiResponse } from 'next'

const handler = async (req: NextApiRequest, res: NextApiResponse) => {
    try {
        const intentUrl = `https://twitter.com/intent/tweet?text=${encodeURIComponent(
            req.body.text
        )}&url=${encodeURIComponent(req.body.url)}`

        // Return the intent URL with the appropriate headers
        res.setHeader('Access-Control-Allow-Origin', '*')
        res.setHeader('Content-Type', 'application/json')
        res.status(200).json({ intentUrl })
    } catch (error) {
        console.error(error)
        res.status(500).json({ error: 'Internal Server Error' })
    }
}

export default handler

and then my tweetReferral here is for fetching the url from my api proxy.

const handleShare = async () => {
  const intentUrl = await tweetReferral({ text, url })

  if (intentUrl && intentUrl?.toString().length > 0) {
    // Open a new popup window with the Twitter intent URL
    // window.open(intentUrl.toString(), 'twitter-share', windowOptions)
   window.open(intentUrl.toString(), '_blank')
  }
}

// usage
<Button onClick={handleShare} colorScheme="twitter">
   share
</Button>
0

There are 0 best solutions below