From 36f4ebc64b4624ad84d0f12d87f2fb529089354d Mon Sep 17 00:00:00 2001 From: David Taylor Date: Tue, 7 Nov 2023 23:44:39 +0000 Subject: [PATCH] DEV: Abort placing adsense if Ember component is destroyed (#190) This should avoid surprising error messages being printed to the console --- .../discourse/components/google-adsense.js | 25 +++++++++++-------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/assets/javascripts/discourse/components/google-adsense.js b/assets/javascripts/discourse/components/google-adsense.js index a2eed30..d357a37 100644 --- a/assets/javascripts/discourse/components/google-adsense.js +++ b/assets/javascripts/discourse/components/google-adsense.js @@ -141,22 +141,27 @@ export default AdComponent.extend({ this._super(); }, - _triggerAds() { + async _triggerAds() { if (isTesting()) { return; // Don't load external JS during tests } this.set("adRequested", true); - loadAdsense().then(function () { - const adsbygoogle = window.adsbygoogle || []; - try { - adsbygoogle.push({}); // ask AdSense to fill one ad unit - } catch (ex) { - // eslint-disable-next-line no-console - console.error("Adsense error:", ex); - } - }); + await loadAdsense(); + + if (this.isDestroyed || this.isDestroying) { + // Component removed from DOM before script loaded + return; + } + + try { + const adsbygoogle = (window.adsbygoogle ||= []); + adsbygoogle.push({}); // ask AdSense to fill one ad unit + } catch (ex) { + // eslint-disable-next-line no-console + console.error("Adsense error:", ex); + } }, didInsertElement() {