Working with RTB ad block code

You can enable the additional functions and change certain settings by directly editing the ad code without using the ad block designer in the interface.

The Ya.Context.AdvManager.render function is responsible for invoking the ad in the code.

Attention. If you do not have sufficient experience working with ad code, it's not a good idea to make your own changes to the ad block code. Any changes to the variables and functions other than those described on this page might lead to errors in the Yandex Advertising Network ad blocks and cause you to lose revenue.

Switching to separate ad code

Starting from July 20, 2021, the ad code is divided into two parts: the unified ad loader code and the ad block code. Previously, different loader codes were used to load different types of blocks. With the new codes, the browser doesn't waste time accessing multiple loaders, so ads are displayed faster. Learn more about the benefits of using split code

The legacy embed codes are compatible with the new codes, so you can gradually change banner codes on the pages of your site. We recommend first changing one of the codes on the page to make sure that it works correctly and then moving on to the next one.

You can get the new ad code via the YAN interface: go to Products → RTB blocks and click Get code next to the desired ad block.

To replace the ad code on your site:

  1. Add the ad loader code to the <head> of each page where the ad is displayed:
    <script>window.yaContextCb = window.yaContextCb || []</script>
    <script src="https://yandex.ru/ads/system/context.js" async></script>
    Copied to clipboard
    Note. The ad loader code is the same for all types of Yandex ads. You don't need to duplicate the ad loader code if the page already has split recommendation widget code or new ADFOX embed codes.
  2. Replace the old ad block code with the new one. You can get the new block code via the YAN interface or change it manually using the example below. Note that when replacing the code manually, you don't need to change the container (the div element):
    An example of replacing the legacy asynchronous code with new asynchronous code
    Legacy asynchronous merged code New asynchronous split code
    <div id="yandex_rtb_R-A-588461-2"></div>
    <script type="text/javascript">
      (function(w, d, n, s, t) {
        w[n] = w[n] || [];
        w[n].push(function() {
          Ya.Context.AdvManager.render({
            blockId: "R-A-588461-2",
            renderTo: "yandex_rtb_R-A-588461-2",
            async: true
          });
        });
        t = d.getElementsByTagName("script")[0];
        s = d.createElement("script");
        s.type = "text/javascript";
        s.src = "//an.yandex.ru/system/context.js";
        s.async = true;
        t.parentNode.insertBefore(s, t);
      })(this, this.document, "yandexContextAsyncCallbacks");
    </script>
    <div id="yandex_rtb_R-A-588461-2"></div>
    <script>
      window.yaContextCb.push(()=>{
        Ya.Context.AdvManager.render({
          renderTo: 'yandex_rtb_R-A-588461-2',
          blockId: 'R-A-588461-2'
        })
      })
    </script>
    An example of replacing the legacy synchronous code with new asynchronous code
    Legacy synchronous merged code New asynchronous split code
    <div id="yandex_rtb_R-A-588461-2"></div>
    <script type="text/javascript">
      (function(w, n) {
        w[n] = w[n] || [];
        w[n].push(function() {
          Ya.Context.AdvManager.render({
            blockId: "R-A-588461-2",
            renderTo: "yandex_rtb_R-A-588461-2",
            async: false
          });
        });
        document.write('<sc'+'ript type="text/javascript"
        src="//an.yandex.ru/system/context.js"></sc'+'ript>');
      })(this, "yandexContextSyncCallbacks");
    </script>
    <div id="yandex_rtb_R-A-588461-2"></div>
    <script>
      window.yaContextCb.push(()=>{
        Ya.Context.AdvManager.render({
          renderTo: 'yandex_rtb_R-A-588461-2',
          blockId: 'R-A-588461-2'
        })
      })
    </script>

Statistical samples for RTB blocks

You can additionally specify sample identifiers (IDs) and collect separate statistics using samples in the RTB block code. The sample ID is provided in a separate variable:

Variable name Description Data type
statId Sample ID A number between 1 and 1000000000

Enter the sample ID in the ad code to be placed on the site. For example:

Ya.Context.AdvManager.render({
    blockId: "R-A-123456-1",
    renderTo: "yandex_rtb_R-A-123456-1",
    statId: 34567, // CROSS SECTION ID
});

For the block R-A-123456-1 from the example, the sample ID is 34567. It can also be specified in other blocks. This will allow you to view group statistics for these blocks. By placing the R-A-123456-1 block on other pages, you can specify a different sample ID to view statistics separately for each placement.

Callback functions in the ad code

You can add the following callback functions to the ad code:
onRender

The onRender callback function allows you to obtain information about whether the ad has been rendered (whether the ad was successfully selected when requested from the RTB system) and which particular ad was shown. The function obtains the data.product parameter with one of two values:

  • direct — Yandex.Direct ads were shown in an RTB ad block.

  • rtb — a media ad was shown in an RTB ad block.

The onRender callback function must be added as the last parameter in the Ya.Context.AdvManager.render function.

An example of code that is used to call an ad with the onRender function
Ya.Context.AdvManager.render({
    blockId: "R-A-123456-1",
    renderTo: "yandex_rtb_R-A-123456-1",
    onRender: (data) => { console.log(data.product); }
})
onError

The onError callback function is called if an error occurred during request execution. When called, it sends the following parameters:

  • type — type of error. It may take the following values:
    1. error — failed to load the ad block.
    2. warning — the ad block was loaded with an error.
  • code — error code.
  • text — text description of the error.
Possible error codes and their values
Type of error Error code What it means How to fix it
error DESKTOP_FULLSCREEN An attempt was made to load an interstitial mobile block on the desktop version of the site. You can only use interstitial ad blocks for the mobile version of the site.
error CONTAINER_NOT_FOUND Couldn't find the container to load the ad. Failed to find the container when loading the code or after receiving ad data from the server. This error usually occurs on pages with dynamic content.
error BLOCK_NOT_FOUND The ad was called, but the RTB block with the specified ID wasn't found. Check the ad code obtained in the YAN interface. Make sure that the block id is correct.
error PAGE_NOT_FOUND The ad was called, but the ad platform with the given ID wasn't found. Check the ad code obtained in the YAN interface. Make sure that the block id is correct.
error WRONG_DOMAIN The domain that called the ad isn't specified in the ad platform settings.

Make sure that the domain you placed the ad block on is specified in the ad platform settings.

If the domain isn't specified, add a new ad platform with this domain and create an RTB block for this ad platform. You can add mirror sites to an existing ad platform.

error PAGE_DISABLED The ad was called, but this ad platform doesn't work. Check the ad platform status in the YAN interface. The ad platform can be stopped, archived, or blocked for violating the YAN Terms of Participation.
error UNKNOWN_BLOCK_TYPE An attempt was made to load an unknown block type. Check the ad code in the YAN interface. Block ID must start with the letters R, D, or Y.
error TOO_SMALL_CONTAINER None of the formats of the given RTB block fit the container for loading ads. Check the size of the container for loading ads. The minimum container size is 160 x 50 pixels.
error VIDEO_ERROR An error occurred when loading the video ad. Check the size of the container for loading ads. The minimum size is 320 x 180 pixels.
warning CONTAINER_IS_HIDDEN An attempt was made to load an ad into a 0 x 0 pixel container (for example, with the display:none style). Hidden containers slow down ad loading. We recommend inserting ad blocks into visible containers.
An example of code that is used to invoke an ad with the onError function
Ya.Context.AdvManager.render({
    blockId: 'R-I-106712-1',
    renderTo: 'block_container',
    onError: (data) => {
        console.log('type', data.type); // Error type: error or warning
        console.log('code', data.code); // error code (see description above)
        console.log('text', data.text); // Text description of the error
                                        
        // Error processing by the platform
    }
});

Displaying your own ads in an RTB block

If the auction doesn't produce a matching offer for your RTB block, you can show your own ads in the block. To do this, add your ad code to the RTB block code.
  1. Get the RTB block code in the YAN interface (RTB blocks → Get code → Copy).
  2. Place the RTB block code on the site.
  3. Add your ad code as the last parameter of the Ya.Context.AdvManager.render function.
An example of code that inserts your own ad
Ya.Context.AdvManager.render({
    blockId: 'R-A-123456-1',
    renderTo: 'yandex_rtb_R-A-123456-1',
}, () => {
    // INSERT YOUR AD CODE HERE
})
If the auction didn't produce a suitable offer, the alternative code is executed, and your own ad is displayed instead of the ad block (not via iframe). Impressions of your own ads are not counted in the YAN statistics.

There is another way to show your own ads: enter the ad code in the YAN interface. The code snippet for displaying your ad will be generated and added to the RTB block code automatically. This way you can use iframe to display your own ads and include these impressions in the YAN statistics.

Ad impressions in infinite scroll feeds

To display ads in infinite scroll feeds, you can use the same ad block and just change the pageNumber parameter and the name of the renderTo container. The unique blockId from the ad block designer remains unchanged.

An example of the ad code for the first ad block
<div id="yandex_rtb_R-A-123456-1-1"></div>
<script>window.yaContextCb.push(()=>{
    Ya.Context.AdvManager.render({
        blockId: "R-A-123456-1",
        renderTo: "yandex_rtb_R-A-123456-1-1", // add 1 at the end of the name
        pageNumber: 1,  // set 1 as the parameter
    })
})</script>
An example of the ad code for the second ad block
<div id="yandex_rtb_R-A-123456-1-2"></div>
<script>window.yaContextCb.push(()=>{
    Ya.Context.AdvManager.render({
        blockId: "R-A-123456-1",
        renderTo: "yandex_rtb_R-A-123456-1-2", // add 2 at the end of the name
        pageNumber: 2,  // set 2 as the parameter
    })
})</script>

Container size for a custom-size ad block

The custom-size block adapts to the size of the container and is suitable for sites with an adaptive layout. Use stylesheets to specify the container size for sites with an adaptive layout.

  1. Add the tag div CSS class yandex-adaptive in the ad code that you obtained in the interface.

    Example
    <div id="yandex_direct_R-A-12345-1" class="yandex-adaptive"></div>
  2. Use media-queries to configure the container to accept various sizes depending on the screen resolution.

    Example
    @media screen and (max-width: 700px) {
        .yandex-adaptive {
            width:200px;
            height:300px;
        }
    }
    
    @media screen and (min-width: 701px) {
        .yandex-adaptive {
            width:336px;
            height:280px;
        }
    }

    This means that on screens up to 700 pixels wide, ads will be displayed in a 200×300 block, and on screens with a width of 701 pixels, a 336×280 block will be used.

Note. If you want the container to always use the same size, specify it in the visual ad block designer in the interface.

If you didn't find the information you were looking for, check the FAQ or contact us.

I inserted code but the ads are not being displayed

Here are a few possible reasons for problems with displaying ads:

  • The ad code was recently installed: the YAN robot requires some time to index the page and link it to ads. Be patient and you will start getting ad impressions.

  • Your ad code was inserted incorrectly: check that your JavaScript ad block code has been correctly installed. Please keep in mind that when copying code, your text editor might truncate or wrap long strings, which might cause the JavaScript code to run incorrectly. Make sure the code does not get modified during copying.

  • Code is not valid for this ad platform: make sure that the inserted ad block code was created for the specific ad platform and not for one of your other ad platforms.

  • Site is banned from indexing: the site must be accessible for indexing by the YAN robot called YandexDirect. If indexing a site or its individual pages is banned (for example, in the robots.txt file), the robot will not be able to index the content of the pages nor select relevant ads for them.

  • Text is wrapped in the <noindex> tag: make sure that the page has text on it and that it has not been excluded using the <noindex> tag. It is not possible to select content-based ads for pages that have no text.

  • Your browser has cached old information: to update the information, press CTRL+F5.

Other issues