簡體   English   中英

腳本在兩種情況下都顯示文本

[英]Script is displaying text on both occasions

我正在嘗試在用戶使用adblock時顯示文本; 我正在使用以下腳本;

ads.js

<script>var canRunAds = true;</script>

index.php

<script data-rocketsrc="ads.js" type="text/rocketscript"></script>
<script type="text/rocketscript">
  if( window.canRunAds === undefined ){
    var x = "Adblock is enabled, Please disabled to continue.";
    document.write (x);
  }
</script>

但是我一直遇到的問題是,在定義變量和未定義變量時都顯示文本。

ads.js ,設置window.canRunAds 您還需要使用typeof檢查undefined

ads.js

window.canRunAds = true;

index.php

<script src="/ads/ads.js"></script>
<script>
  if (typeof window.canRunAds === 'undefined') {
    var x = "Adblock is enabled, Please disabled to continue.";
    document.write (x);
  }
</script>

正如雅克已經指出的那樣,在檢查未定義的變量時使用typeof運算符。 參見https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Operators/typeof

在您的代碼中,將檢查window.canRunAds與

typeof(window.canRunAds) === 'undefined'

因為我們可以肯定,父對象窗口肯定是在您的上下文中定義的。 如果它將是我們不知道的對象,請首先檢查typeof(window)==='undefined'以獲取錯誤。

干杯!

注意

如果不清楚,則應將每個示例中的第一個內聯<script>替換為<script src="/ads/ads.js"></script>才能正常工作。 我就是不能在這里做。

tl; dr

在網站上,您的ads.js文件是使用data-rocketsrc="ads.js"異步加載的。 將其替換為src="ads.js"以在下一個內聯腳本執行之前同步加載它。 您的頁面(省略CloudFlare )應如下所示:

<html>

<head>
  <title>Test Adblock</title>
  <script src="ads.js"></script>
</head>

<body>
  <script>
    'use strict';
    if (typeof canRunAds === 'undefined') {
      document.write('canRunAds is being blocked<br/>');
    }
  </script>
</body>

</html>

並且https://flamingocams.com/ads/ads.js的內容應為:

var canRunAds = true;

當前它具有以下內容:

<script>var canRunAds=true;</script>

我會承認我不是robotscript方面的專家,但是我的猜測是,使用該預處理程序的腳本的運行上下文不是window 作為常規JavaScript運行它,以確保在window上下文中同步執行。

回答

只需使用typeof canRunAds === 'undefined' 無需使用window.canRunAds ,因為即使在strict modetypeof也會在檢查未聲明的變量時抑制任何可能的ReferenceError

 <script> 'use strict'; var canRunAds = true; // to demonstrate the conditional `if` works // var someOtherFlag = true; </script> <script> 'use strict'; if (typeof canRunAds === 'undefined') { document.write('canRunAds is being blocked<br/>'); } if (typeof someOtherFlag === 'undefined') { document.write('someOtherFlag is being blocked<br/>'); } </script> 

但是,通常在頁面上基於CSS這樣有條件可見的元素是通常的做法:

 p.adblock-warning { display: none; color: red; } body.adblock p.adblock-warning { display: initial; } 
 <script> // assume this couldn't run // var canRunAds = true; </script> <script> if (typeof canRunAds === 'undefined') { document.body.classList.add('adblock'); } </script> <p class="adblock-warning">Adblock is enabled, Please disabled to continue.</p> 

顯示內容

[英]displaying content of <script type=“text/html”

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM