The script is showcasing text on both instances

I am currently working on a script to show text to users who are using adblock. The script I am using is as follows:

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 message = "Adblock is enabled. Please disable it to continue.";
    document.write (message);
  }
</script>

However, I have encountered an issue where the text is displayed even when the variable is defined.

Answer №1

To ensure that ads can run on your website, you will need to make changes to the ads.js file by setting the variable window.canRunAds to true. Additionally, use typeof to check if the variable is undefined.

ads.js:

window.canRunAds = true;

index.php:

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

Answer №2

Important Note

If it was not obvious, the initial inline <script> in each example needs to be swapped with

<script src="/ads/ads.js"></script>
for proper functionality. Unfortunately, I am unable to make that change at this time.

Summary

On your website, the ads.js file is loaded asynchronously using data-rocketsrc="ads.js". To ensure it loads synchronously before the next inline script runs, replace it with src="ads.js". Your page should appear as follows (excluding 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>

The content of

https://flamingocams.com/ads/ads.js
should simply be:

var canRunAds = true;

Currently, it contains:

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

I must confess, my expertise in rocketscript is limited, but I suspect the running context might not be window. Run it as regular JavaScript to ensure synchronous execution in the window context.

Solution

Just utilize typeof canRunAds === 'undefined'. Using window.canRunAds is unnecessary, as typeof handles any possible ReferenceError when checking an undeclared variable, even in strict mode:

<script>
  'use strict';
  var canRunAds = true;
  // demonstrating the conditional `if`
  // 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>

Typically, having a conditionally visible element based on CSS is more common practice:

p.adblock-warning {
  display: none;
  color: red;
}

body.adblock p.adblock-warning {
  display: initial;
}
<script>
  // assuming 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>

Answer №3

To determine if a variable is undefined, Jacques suggested using the typeof operator. You can learn more about this at https://developers.mozilla.org/de/docs/Web/JavaScript/Reference/Operators/typeof.

In your specific scenario, you would check for window.canRunAds like this:

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

This approach works because we know that the parent object window is definitely defined within your code. If you are unsure about an object's definition, start by checking typeof(window) === 'undefined' to avoid errors.

Cheers!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Toggle the visibility of a component in React by managing its state

Currently, I am faced with the challenge of toggling the visibility of a component based on a state value: import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css'; import Button from ' ...

Is it possible to find out which JavaScript file the AJAX function is using to send a request to a Java servlet?

I am facing an issue with two js files, one.js and two.js. Both of these files make ajax requests to the same Java servlet class(AppController.java). Here is the code from one.js: function addOne(){ var formData = $('#form1').serialize(); ...

AngularJS Partial Views: Enhancing Your Website's User Experience

As a newcomer to the world of Angular, I am seeking guidance on a specific issue. I have encountered a one-to-many relationship scenario where one Category can have multiple Product items. The challenge lies in my layout page setup where I display various ...

Is it advantageous to combine socket.io with express for seamless communication in web applications? If the answer is yes, what is the best approach to integrating

Embarking on my journey into back-end development, I am currently delving into the task of creating a simulated money poker website. Leveraging Node.js along with socket.io, express-session, and passport, I initially relied heavily on express with an HTTP ...

Utilizing JavaScript for loops to extract the final element from an array

I am facing an issue with the second loop within a function that goes through a JSON file. The problem is that it only returns the last item in the array. I need to figure out how to fix this because the chart object should be created on each iteration, ...

Provide the identification number of a specific row within the modal

I am trying to pass the id of a specific row into a modal popup Link code: <a href="#myModal" class="btn btn-default btn-small" id="custId" data-toggle="modal" data-id="<? echo $row['id']; ?>">Resume</a> Modal code: <div ...

Filtering tables in Angular 6 using checkbox options

I have a functional code snippet that filters a table using checkboxes. However, I am facing an issue when unchecking a checkbox. It does not return the original array as expected. .html <ng-container *ngFor="let group of groups"> <label cla ...

How to Implement Click Actions on Elements in AngularJS

Just starting out with angularjs and I have a scenario with jQuery. handleClick(); function handleClick() { var doubleClick = false; $('#text span.word').on('click', function() { var that = this; setTimeout(funct ...

Adjusting the backdrop hues

My goal is to change the background colors of my website by cycling through all possible combinations. However, I'm encountering issues with my code and can't figure out what's wrong. var red = 0; var green = 0; var blue = 0; do { do ...

Disabling the child element from triggering the parent element's onclick function, while still allowing it to respond to its own content

My list elements have onclick-functions that change the display of each element and its child div, moving them to the top of the list. Clicking again reverses this effect. The issue arises because the child div contains search fields, clickable pictures, ...

Non-functioning Tooltips on Google Charts

Currently, I am working on integrating Google Chart with ASP.NET and linking it to a SQL Server database. I have encountered an issue while attempting to customize the tool tip. Below is the Header Code: <script src="js/jquery/jquery-1.10.2.js" type=" ...

Incorporating an image within a v-for loop in Vuetify

I am planning to incorporate images at a later stage, but I am currently utilizing v-for and facing a dilemma of how to seamlessly introduce the image within the loop without disrupting its flow. <template> <v-card> <p v-for="item ...

What is the solution for handling undefined errors that occur when employing d3.select(this) within a Vue methods hook?

Currently, I am in the process of transferring d3 graphs from another project to my personal Vue-based project. Most aspects are functioning as expected, except for aligning labels in the arcs of a pie chart using the arc.centroid(d) method. Two errors kee ...

The method you are trying to call is not defined in Laravel

I recently developed a basic CRUD blog application with tags functionality. I have integrated tags into my pages and implemented the use of Select JS for selecting and editing tags in input fields. Now, my goal is to have the input field pre-populated wit ...

Angular-ui-bootstrap modal failing to display provided data

I have been working on implementing model data into a modal window that opens. The data is passed through a $http.post success and also in failure then() with different titles and button texts. Several data points are being passed to the modal: //.then(){ ...

Is there a way to update a data element within a $.get request by utilizing information from a JSON array?

Is there a way to dynamically change a data element in a $.get request using values from a JSON array? Let's take a look at an example code snippet that achieves this: $.get(url, { 'p': testerName, ...

What is the most efficient method for transforming an index into a column number that resembles that of Excel using a functional approach?

Is there a way to write a function that can produce the correct column name for a given number, like A for 1 or AA for 127? I know this question has been addressed numerous times before, however, I am interested in approaching it from a functional perspect ...

Is it possible to display partial html templates by accessing the local url and blending them with the main index.html file?

Is there a way to view partial HTML templates locally without copying them into the main index.html file? I'm looking for a solution that allows me to access my partial templates through a local URL without having to manually paste them into the main ...

When switching tabs in Javascript, the page does not automatically reload. However, the page will reload only when it is on

After writing a code using javascript/Youtube API + PHP to fetch a YT video ID from a MySQL server and place it in Javascript, I realized that the page only reloads when the tab is active and not when it's in the background. This issue disrupts the wh ...

Encountering a null pointer exception when launching the Chrome browser using Selenium

Hope you all are doing well. I need assistance in resolving a null pointer issue while developing a new Selenium framework for my company. The problem arises after calling the method "StartBrowser()" from the base class in the browser class. Everything ru ...