javascript – Audio.get does not work via VKApi on js

Question:

So the first thing I did was this:

<script src="http://vk.com/js/api/openapi.js" type="text/javascript"></script>

Then index.js wrote this in index.js :

VK.init({
   apiId: ********
   });

VK.Auth.login(function(response) {
   });

VK.api("audio.get", {uid:viewer_id,count:count}, function(data) {
   alert(data.response);
   var obj_respone = eval('('+ data.response +')');;
   for(var i=0; i<data.response.length; i++){
     document.getElementById('tracks').innerHTML+="<a href="+data.response[i].url+">"+data.response[i].artist +'-'+data.response[i].title+"</a><br />";
   }
   });

Then I wrote electron in the terminal. The default authorization window opens, log in, and that's it. Nothing works. Please help me very much.

Answer:

  1. When authorizing a user, you do not ask for access rights to audio recordings.
  2. You have an error concatenating the string near the href – the attribute will not have quotes.
  3. VK.Auth.login() is an asynchronous method.
  4. In the loop, you iterate over the response object, but you need to iterate over the response.items object, which contains an array of audio recordings.

Sample code:

VK.init({
    apiId: 123456
});

VK.Auth.login(function (response) {
    VK.api('audio.get', {
        uid: viewer_id,
        count: count
    }, function (data) {
        if (data.error) {
            alert('VK API error #' + data.error.error_code + ': ' + data.error.error_msg);

            return;
        }

        for (var i = 0; i < data.response.items.length; i++) {
            document.getElementById('tracks').innerHTML += '<a href="' + data.response.items[i].url + '">' + data.response.items[i].artist + '-' + data.response.items[i].title + '</a><br>';
        }
    });
}, 8); // доступ к аудиозаписям

UPD

It looks like you are developing for Electron. If so, then the Open API will not work for you, because the Open API is intended for websites with a domain name. You need to use direct API requests and create a standalone application in VK.

Scroll to Top