kaiads-glue.js 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // Glue connecting Puzzles to the KaiAds API.
  2. //
  3. // The Kai Store requires that we support advertisements through
  4. // KaiAds. To avoid polluting the Puzzles core with this, the
  5. // relevant code is largely confined to this file. It can then be
  6. // included in builds that are destined for the Kai Store and left out
  7. // of others. The main puzzle code, and the KaiAds API (as supplied
  8. // by Kai Technologies) should be loaded before this file.
  9. (function() {
  10. // To run, we need to be on KaiOS with the KaiAds SDK and the
  11. // Open Web Apps API.
  12. if (window.getKaiAd === undefined || navigator.mozApps === undefined ||
  13. navigator.userAgent.toLowerCase().indexOf('kaios') == -1) return;
  14. // If those prerequisites are satisfied, install the button.
  15. var advertbutton = document.createElement("button");
  16. advertbutton.type = "button";
  17. advertbutton.textContent = "Display an advert...";
  18. advertbutton.disabled = true;
  19. var advertli = document.createElement("li");
  20. advertli.appendChild(advertbutton);
  21. var topmenu = menuform.querySelector("ul");
  22. var before = topmenu.querySelector(":scope > li:nth-last-child(2)");
  23. topmenu.insertBefore(advertli, before);
  24. // Now work out whether we're installed from the Store (and hence
  25. // want real adverts) or not (and hence want test ones).
  26. var selfrequest = navigator.mozApps.getSelf();
  27. selfrequest.onerror = function() {
  28. console.log("Error getting own app record: ", selfrequest.error.name);
  29. // Leave the button disabled.
  30. };
  31. selfrequest.onsuccess = function() {
  32. var testmode = selfrequest.result.installOrigin !=
  33. "app://kaios-plus.kaiostech.com";
  34. advertbutton.addEventListener("click", function(e) {
  35. // The KaiAds SDK provides this function.
  36. getKaiAd({
  37. publisher: 'dac9c115-ec42-4175-ac5e-47e118cc541b',
  38. test: testmode ? 1 : 0,
  39. timeout: 10000,
  40. onready: function(ad) {
  41. ad.on('close', function () {
  42. // KaiAds adds inline styles to the body and doesn't
  43. // remove them, so we do it ourselves.
  44. document.body.style = '';
  45. onscreen_canvas.focus();
  46. });
  47. ad.call('display');
  48. },
  49. onerror: function(err) {
  50. alert(`Sorry; no advert available (KaiAds error ${err}).`);
  51. onscreen_canvas.focus(); // Close the menu.
  52. }
  53. });
  54. });
  55. advertbutton.disabled = false;
  56. };
  57. })();