plugin.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /* eslint-env browser */
  2. require(['gitbook'], function (gitbook) {
  3. var adInsertPoint = '.page-inner section'
  4. , adPosition = 'bottom'
  5. , ad;
  6. gitbook.events.bind('start', function (e, cnf) {
  7. const config = cnf.adsense;
  8. // Use custom insert point if defined
  9. if (config.element) {
  10. adInsertPoint = config.element;
  11. }
  12. // Use custom position if defined
  13. if (config.position) {
  14. adPosition = config.position;
  15. }
  16. // Inject script to head.
  17. var adsByGoogleScript = document.createElement('script');
  18. adsByGoogleScript.src = '//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js';
  19. adsByGoogleScript.setAttribute('async', true);
  20. document.body.appendChild(adsByGoogleScript);
  21. // Generate <ins> (ad)
  22. ad = document.createElement('ins');
  23. ad.style = 'display: block';
  24. ad.className = 'adsbygoogle';
  25. ad.setAttribute('data-ad-client', config.client);
  26. ad.setAttribute('data-ad-slot', config.slot);
  27. ad.setAttribute('data-ad-format', config.format);
  28. // Add the ad to the DOM
  29. var element = document.querySelector(adInsertPoint);
  30. if (adPosition === 'top') {
  31. element.insertBefore(ad, element.firstChild);
  32. } else {
  33. element.appendChild(ad);
  34. }
  35. (adsbygoogle = window.adsbygoogle || []).push({}); // eslint-disable-line
  36. });
  37. // I insert ad again when switching pages
  38. gitbook.events.bind('page.change', function () {
  39. if (ad) {
  40. var element = document.querySelector(adInsertPoint);
  41. if (adPosition === 'top') {
  42. element.insertBefore(ad, element.firstChild);
  43. } else {
  44. element.appendChild(ad);
  45. }
  46. }
  47. });
  48. });