Why does my code work in console but not when it runs on the web page? [closed]

1 day ago 1
ARTICLE AD BOX

Hoping someone can help explain why this snippet of code fails when it runs the script on the web page, but then if I open the console and run the exact same code on the same page, it works properly.

The script uses a function to call a javascript wrapper for the API at TMDB.com

Here's the function I'm using to call the javascript TMDB wrapper:

function tmdbSearch(qString, qDate = null) { const apiv3Key = < snipped > ; const v3Client = v3(apiv3Key); console.log(v3Client); if (qDate !== null) { v3Client.configuration.api() .then((apiConfiguration) => { v3Client.search.tv({ 'query': qString, 'first_air_date_year': qDate }) .then(({ results }) => { console.log(results); tmdbParse(results); }); }) .catch((error) => { console.log('error', error); }); } else { // qDate was not supplied when calling tmdbSearch v3Client.configuration.api() .then((apiConfiguration) => { v3Client.search.tv({ 'query': qString }) .then(({ results }) => { console.log(results); tmdbParse(results); }); }) .catch((error) => { console.log('error', error); }); } }

When the script is loaded, it calls the above search function with whatever title the page is searching for. For example:

tmdbSearch("Example Title")

The console shows the expected output for the console.log(v3Client) line, but for the console.log(results) line it just shows an empty array.

Here's the puzzling bit: after that, if I open the console and manually run:

tmdbSearch("Example Title")

...then the console.log(results) line successfully shows an array populated with TMDB search results.

So the code seems to work when I run it manually, but not when the function is called automatically by the script itself.

As a workaround I tried wrapping the function call in a setTimeout:

setTimeout(() => { tmdbSearch("Example Title") }, 2500)

...so that the tmdbSearch() function doesn't get called until 2.5 seconds after the page has loaded — similar to me manually inputting the command into the console after the page has loaded.

But I got the same results — empty array when the page runs the command, properly populated array when I run it manually on console.

What am I missing here?

In case it helps, here's the JavaScript API wrapper I'm using:

https://pastebin.com/P5DE4Zfz

(Sorry that wrapper is formatted so poorly, that's the way the author posted it)

Anyone have any insights as to why this works in console but not when run by the script/page?

Read Entire Article