M
M
mirapi2018-05-14 01:38:58
In contact with
mirapi, 2018-05-14 01:38:58

How to create a VK community widget?

Good day!
Recently I wanted to make my own widget for the community, which would report some statistics. In the VK documentation, everything is described rather complicatedly, without examples, rather than as described for the same bots. Couldn't figure it out on my own.
An internet search didn't turn up much results. I found only one solution , but for some reason it didn't save me. I did everything as described in the answer, but when you click on either of the two buttons, absolutely nothing happens. Of course, I do this after adding it to the iframe through the application itself. The page is loading but nothing is happening. Perhaps someone else has a solution, or ready-made code for an example?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Sokolov, 2018-05-14
@sergiks

An easy way
There is a ready-made free application for Communities "LiveWidget" - there you only need to write the code for the widget itself. There are three dots in your community menu - Community Management - Applications, scroll through the list of suggested applications to LiveWidget, click "Add":

screen
5af95de14a7d2991085711.png
The Jedi way
The documentation for creating a community widget explains everything in detail. In short:
  1. create app - Embedded App - Community App
  2. specify your server and the folder where, for example, such HTML is located with the address of the iframe
  3. go to your Community - menu Community Management - Applications - select your freshly created application there
  4. give it permission to add widgets
  5. paste the code of your widget and make a preview of it - if there are no errors in the widget code, a pop-up window will show how it looks and offer to install it in the community.
Application Screen
5af9668c9208d318099967.png
Application code
<!DOCTYPE html>

<html lang="">
<head>
    <meta charset="utf-8">

    <title>Widgeteer</title>
    <meta name="description" content="Создание виджета для сообщества ВКонтакте">
    <meta name="keywords" content="Sergei Sokolov,ВК,виджет,конструктор">
    <meta name="robots" content="noindex,nofollow">
    
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
</head>

<body>
  <div class="container">
    <h3>Виджет для сообщества ВК</h3>
    
    <div id="b-alerts"></div>
    
    <div class="form-group">
      <button id="btn-permission" class="btn btn-primary" type="button">Дать разрешение</button>
    </div>

    <div class="form-group">
      <label for="in-type">Тип виджета:</label>
      <select class="form-control" id="in-type">
        <option value="text">text</option>
        <option value="list">list</option>
        <option value="table">table</option>
        <option value="tiles">tiles</option>
        <option value="compact_list">compact_list</option>
        <option value="cover_list">cover_list</option>
        <option value="match">match</option>
        <option value="matches">matches</option>
      </select>
    </div>
    
    <div class="form-group">
      <label for="in-code">Код виджета:</label>
      <textarea rows="7" class="form-control" id="in-code">return {
"title": "Цитата",
"text": "Текст цитаты"
};</textarea>
    </div>

    <button id="btn-preview" class="btn btn-primary" type="button">Предпросмотр виджета</button>
        
  </div><!-- /.container -->
  
  
  

  <!-- Bootstrap JavaScript -->
  <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js" integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T" crossorigin="anonymous"></script>
  <!-- /Bootstrap JavaScript -->
  
  <!-- main script -->
  <script>
    function onReady() {

      // Слушать события предпросмотра виджета 
      VK.addCallback('onAppWidgetPreviewFail', function(e){
        console.error('onAppWidgetPreviewFail', e);
        showAlert('warning', 'onAppWidgetPreviewFail');
      });
      
      VK.addCallback('onAppWidgetPreviewCancel', function(e){
        console.error('onAppWidgetPreviewCancel', e);
        showAlert('info', 'onAppWidgetPreviewCancel');
      });
      
      VK.addCallback('onAppWidgetPreviewSuccess', function(e){
        console.log('onAppWidgetPreviewSuccess', e);
        showAlert('success', 'onAppWidgetPreviewSuccess');
      });
      
      // События нажатия на кнопки
      $('#btn-permission').on('click', function(){
        console.log('showGroupSettings');
        VK.callMethod("showGroupSettingsBox", 64);
      });
      
      $('#btn-preview').on('click', function(){
        var type = $('#in-type').val(),
          code = $('#in-code').val()
        ;
        
        console.log('showAppWidgetPreviewBox', {type: type, code:code});
        VK.callMethod("showAppWidgetPreviewBox", type, code);
      });

    }


    function showAlert(className, text) {
      var html = [
        '<div class="alert alert-dismissible alert-'+className+'" role="alert">',
          text,
        '</div>',
      ].join('\n');
      $('#b-alerts').append(html);
    }
  </script>
  <!-- /main script -->
  

  <!-- VK scripts -->
  <script src="https://vk.com/js/api/xd_connection.js?2"  type="text/javascript"></script>
  
  <script type="text/javascript">
    VK.init(function() {
       // API initialization succeeded
       onReady();
       
    }, function() {
       // API initialization failed
       // Can reload page here
       console.error('VK init error', arguments);
    }, '5.74');
  </script>
  <!-- /VK scripts -->

</body>
</html>

For the types of widgets, see the appWidget object's documentation page .
What specific step in this scenario didn't work for you?

R
romanovcmc, 2019-01-18
@romanovcmc

This solution didn't work either. I cut the vk_height.js file to this code and it worked

$(document).ready( function(){
//Вызываем функцию регулировки высоты каждые пол секунды.
setInterval('autosize(607)', 500); 

$('#set-permission').on('click', function(e) {
e.preventDefault();

// запрос прав доступа для дальнейшего обновления данных посредством крона
// после запрса создается ключ, который можно посмотреть на странице управления сообществом
// его и нунжно будет применить для обновления данных в виджете через сервер
// дока прав тут https://vk.com/dev/permissions
// дока метода тут https://vk.com/dev/clientapi?f=3.+showGroupSettingsBox
VK.callMethod("showGroupSettingsBox", 64);
});

$('#set-widget').on('click', function(e) {
e.preventDefault();

// запрос установки виджета
// типы виджетов можно глянуть тут https://vk.com/dev/objects/appWidget
// как подключить виджет можно глянуть тут https://vk.com/dev/apps_widgets
VK.callMethod('showAppWidgetPreviewBox', 'text', 'return {' + 
'"title": "Цитата",' + 
'"text": "Текст цитаты"' + 
'};');

// типы событий, генерируемых после выполнения запроса на установку виджета можно глянуть тут https://vk.com/dev/apps_widgets
// работа с событиями вк https://vk.com/dev/Javascript_SDK?f=4.1.+VK.addCallback
VK.addCallback('onAppWidgetPreviewSuccess', function f(data){ 
alert("Виджет успешно добавлен"); 
});
});	

});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question