脚本在两种场合都显示文本

时间:2016-07-26 14:41:31

标签: javascript adblock rocketscript

我正在尝试在用户使用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>

然而,我遇到的问题是在定义变量时以及未定义变量时显示文本。

3 个答案:

答案 0 :(得分:1)

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>

答案 1 :(得分:0)

正如Jacques已经指出的那样,在检查未定义的变量时使用typeof运算符。请参阅https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Operators/typeof

在您的代码中,可以使用

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

因为我们可以确定,父对象窗口肯定是在您的上下文中定义的。如果它是我们不知道的对象,首先检查typeof(window)==='undefined'以不出错。

干杯!

答案 2 :(得分:0)

注意

如果不清楚,则每个示例中的第一个内联<script>应替换为<script src="/ads/ads.js"></script>才能生效。我在这里不能这样做。

TL;博士

在网站上,使用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>

我承认我不是rocketscript的专家,但我的猜测是使用该预处理器的脚本的运行上下文不是window。将其作为常规JavaScript运行,以保证在window上下文中同步执行。

答案

只需使用typeof canRunAds === 'undefined'即可。没有必要使用window.canRunAds,因为typeof在检查未声明的变量时会抑制任何可能的ReferenceError,即使在strict mode中也是如此:

<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>

相关问题