onContext.game empty unless Streamer changes game

Hi,

I’m building a simple extension that gets the game currently played before matching it with an external API to show other info about it.

When the extension loads for the first time, it tries to get the game played from twitch.ext.onContext, but it’s always undefined.

After that, when the streamer updates the game currently played, in the stream option, the callback happens properly and I get the game name, so all good here. My issue is with the initial failure in getting the game name.

I don’t use the rig and here are relevant part of code (I think):

const [query, setQuery] = useState(() => {
    return "";
  });

useEffect( () => {
    getGamePlayed();
  }, []);

  const getGamePlayed = () => {
    const data = window.Twitch.ext.onContext(function(context) {
      setQuery(context.game);
      return context.game;
    });
  };

Thanks for your help!

You need to set your onContext top level. Not inside a function. It will fire once when it first loads but you miss that opportunity if you leave it in a sub function.

1 Like

Thanks @WLG3R, I’ve tested adding it directly in a script tag on the index.html page (I’m on local test right now, so script tags do fire properly), but no success, I get the exact same result.

Do you reckon this is the correct way of getting the game currently played, on page load?

I don’t know how much top level I can put it :confused:

<script>
      window.Twitch.ext.onContext(function(context, changed) {
        console.log(context);
        console.log(changed);
      });
    </script>

Inline script tags are not permitted in extensions. So this shouldn’t work.

This gist I wrote is handy for testing extension features.

Thanks Barry, I’ve just tried understanding what’s up with your test kit.

As some of my earlier testing showed, context.game is just an empty string (until the streamer updates the game played in the stream setting).

Any idea where to go from here? Do you have to authenticate in any way before being able to access this data? Would seem weird, as all other data get passed easily.

You might be suffering from

if you are testing as a panel.

Yep, seems to be it!

Thanks Barry, the issue is still there but at least I’m reassured that I’m not crazy.