FriendlyCaptcha / friendly-challenge

The widget and docs for the proof of work challenge used in Friendly Captcha. Protect your websites and online services from spam and abuse with Friendly Captcha, a privacy-first anti-bot solution.
https://friendlycaptcha.com
MIT License
415 stars 61 forks source link

"ReferenceError: window is not defined" in nuxt.js #13

Closed madebyfabian closed 3 years ago

madebyfabian commented 3 years ago

Hey there, I wanted to try this package out, but it's impossible with nuxt.js (a vue.js framework).

I installed it regularly with npm install --save friendly-challenge.

Here is my code

<template>
  <form>
    ...
    <div class="frc-captcha" data-sitekey="<my-sitekey-is-here>"></div>
    <button type="submit">Submit</button>
  </form>
</template>

<script>
  import 'friendly-challenge/widget'

  ...
</script>

The error message

image As you can see in the image, it's coming from node_modules\friendly-challenge\widget.js in line 295.

I am unable to use this package, is there any solution for it?

gzuidhof commented 3 years ago

We should be able to find a workaround for this :), I imagine this error happens when you are using SSR (server side rendering), where there is no Window object. I'm not familiar with Nuxt, but perhaps you can try putting it inside a client-only tag? Let me know if that works.

You may still need to polyfill window as well, something like globalSelf.window = globalSelf, but that's not very pretty.

If that doesn't work, you could perhaps not include it in your bundle and instead use a script tag (i.e. not bundling it).

madebyfabian commented 3 years ago

@gzuidhof Thank you for your quick answer! Appreciate it!

I will close this since I found a solution. The tag would not be any helpful, since the script is importing at the server-side.

Solution

The solution is to import the script only on the client with:

<script>
  export default {
    created() {
      if (process.client)
        import('friendly-challenge/widget')
    }
  }
</script>

Thank you again for your quick help with this!

gzuidhof commented 3 years ago

Perfect :) you're welcome