Option 1
This API you're using is not meant to be used as a regular JSON response, but rather a JSONP, which is a technique created to not only return you a JSON payload as response, but actually it returns executable JavaScript code, based on the request.
You see, on the request URL, https://suggestqueries.google.com/complete/search?client=youtube&ds=yt&q=skrillex&callback=suggestCallback
, notice the last parameter on the call, which is the name of the callBack to be called automatically, from the response returned JavaScript code.
In this case your callback is named suggestCallback
which means, the response JavaScript code, expects that there is a function declared with the name suggestCallback
within the page, which gets automatically called when the response arrives, passing it the correct JSON payload.
To execute this code as a JSONP, the correct code would be :
(...)
<script>
let myArray = [];
const url='https://suggestqueries.google.com/complete/search?client=youtube&ds=yt&q=skrillex&callback=suggestCallback';
function suggestCallback(j) {
console.log("myArray is currently ", myArray);
myArray = j;
console.log("myArray is now ", myArray);
}
function go() {
const script = document.createElement("script");
script.type = "text/javascript";
script.src = url;
document.body.appendChild(script);
}
</script>
(...)
So at this point, the only thing you would need to do is trigger the go()
function from whatever action you want (ex: click of a button, body onload, etc.) and this code, would dynamically create a <script>
tag, pointing to the API specified by url
in the example. Of course you could pass the url
as an argument of a go(url)
function if for instance some parameters on the URL would be more dynamic.
Option 2
Let's say you still want to use the fetch
call as you have it.
In that case, the top part of the code would remain the same, only the go()
function from my code would need to be changed.
In the new version, you also have 2 options, 1 is to execute directly eval
which immediately tries to execute whatever JavaScript code you pass as a string to this function, or you can dynamically create a new <script>
element, setting its text
property to the JavaScript source to be executed.
The code for the go()
function would then be :
(...)
function go() {
fetch(url)
.then((response) => response.text())
.then((src) => {
// eval(src); // you could directly eval the response JS code
// or you can use the traditional way of creating a script element
const script = document.createElement("script");
script.type = "text/javascript";
script.text = src;
document.body.appendChild(script);
});
}
(...)
I wrote this post to explain the expected way how to handle URLs that return JSONP payloads. The previous solutions are what I would consider a workaround, to extract the JSON payload from a JSONP payload, which is not the expected way to handle this kind of calls.