Experiment with re-rendering advertisements using Vue.js

Hey there, I'm new around here so please be patient with me if I make any mistakes :D So, onto my question! I have a website built with vuejs and I want to incorporate some ads into it. To do this, I have created some components:

<template>
  <div class="ad-wrapper">
    <div ref="ad"></div>
    <div id='div-gpt-ad-1407836229438-0' ref="adGpt"></div>
  </div>
</template>

<script>
export default {
  name: 'Ad-top',
  props: {
  },
  components: {
  },
  data() {
    return {
    };
  },
  methods: {
    setAd() {
      const adScript = document.createElement('script');
      adScript.type = 'text/javascript';
      adScript.text = `googletag.cmd.push(function() {
        googletag.defineSlot('/53015287/aniflix.tv_d_970x90_1', [970, 90], 'div-gpt-ad-1407836229438-0').addService(googletag.pubads());

        googletag.pubads().enableSingleRequest();
        googletag.enableServices();
      });`;
      this.$refs.ad.appendChild(adScript);

      const adGptScript = document.createElement('script');
      adGptScript.type = 'text/javascript';
      adGptScript.text = `googletag.cmd.push(function() { googletag.display('div-gpt-ad-1407836229438-0'); });`;
      this.$refs.adGpt.appendChild(adGptScript);
    },
    refreshAd() {
      this.$refs.ad.innerHTML = '';
      this.$refs.adGpt.innerHTML = '';
      this.setAd();
    },
  },
  mounted() {
    this.setAd();

    this.$eventBus.$on('refreshAds', () => {
      this.refreshAd();
    });
  },
  beforeDestroy() {
    this.$eventBus.$off('refreshAds');
  },
};
</script>

Everything seems to be working fine, except when I navigate to another page on my website, the ads don't refresh and disappear.
I attempted to simply clear the tags

refreshAd() {
      this.$refs.ad.innerHTML = '';
      this.$refs.adGpt.innerHTML = '';
      this.setAd();
    },

But unfortunately that didn't work. Does anyone have any ideas?

Answer №1

After some trial and error, I came across a better solution instead of clearing the inner HTML, Google actually provides a refresh attribute. So, I simply replaced

refreshAd() {
      this.$refs.ad.innerHTML = '';
      this.$refs.adGpt.innerHTML = '';
      this.setAd();
    },

with:

refreshAd() {
googletag.cmd.push(function() { googletag.pubads().refresh(); });
},

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

The Postman post request is successful, however when using Axios to make the same request to the URL, a

I am currently using a Rails backend in combination with a Vue frontend. When I make a request to http://localhost:3000/login and include the following request body: {"user": { "email": "<a href="/cdn-cgi/l/email- ...

Detecting when the Ctrl key is pressed while the mouse is hovering over an element in React

In my project, I have implemented a simple Grid that allows users to drag and drop items. The functionality I am trying to achieve is detecting when the mouse is positioned on the draggable icon and the user presses the Ctrl key. When this happens, I want ...

Make sure to select the checkbox using a protractor only if it hasn't been checked already

I am attempting to retrieve a list of checkboxes using CSS and only click on a checkbox if it is not already selected. I have successfully obtained the list, but I am encountering an issue when trying to validate whether or not the element is selected. Ca ...

Encountering issues with extension CLI - "Unable to utilize the import statement outside a module"

Recently, I've been attempting to integrate the Afinn-165 node package (https://www.npmjs.com/package/afinn-165) into my Google Chrome extension. The goal is to analyze the sentiment of text scraped from each page. Being a novice in web development, I ...

"Create a dynamic entrance and exit effect with Tailwind CSS sliding in and out from

My goal is to create a smooth sliding animation for this div that displays details of a clicked project, transitioning in and out from the right side. This is my attempt using Tailwind CSS: {selectedProject !== null && ( <div classNam ...

Displaying JavaScript - Nothing to Echo in PHP

Using PHP to echo a JavaScript block, I have encountered an error message. echo "<script language='javascript' type='text/javascript'> jQuery(document).ready(function($){ var $lg = $('#mydiv'); ...

Utilizing Vue 3 to transform an item within a list by referencing its index

Storing the element's index in a global variable is causing issues when trying to individually edit each of them. Adding multiple elements with similar properties but being unable to edit them separately due to alterations affecting the rest is a chal ...

Check to see if the item is not already in the cart, and if so, add it and then increase its quantity

Utilizing React context, I have implemented a simple logic to add products to the cart using the useReducer hook for adding items. If we look at the Redux Toolkit implementation, here is my redux logic: const cartItemSlice = createSlice({ name: " ...

Leverage the power of puppeteer alongside webpack

Struggling to make puppeteer work with webpack? Despite adding it to package.json and configuring webpack.dev, the 'launch' function still throws errors. Here's what I've tried: Installed dependency in package.json: npm i puppeteer In ...

Best practices for consuming streams using jQuery

Looking to extract VU meter data from my shoutcast server in a continuous live stream format with the following structure: "0xa5 leftVal rightVal 0xa5 leftVal ..... etc" My goal is to capture and decipher this data using JavaScript (jQuery) for animated ...

Building a Vue.js datepicker in Vue.js 1.0.2: A Step-by-Step Guide

Recently delving into the world of vue js, I embarked on a quest to implement vuejs datepicker on version 1.0.27 following the guidelines laid out in the official documentation. My application's current version is also 1.0.27. Seeking to install npm i ...

Instructions on creating a function within the setState() function

This piece of code was created for a React application. The goal is to continuously add a certain number to the state every set interval when the 'AGGIUNGI JACK' button is clicked. However, upon clicking the button, an error message is displayed: ...

Rendering an array of objects in Three JS

I am encountering an error while trying to render an array of objects in a three.js scene. The error message from three.js reads as follows: three.module.js:8589 Uncaught TypeError: Cannot read property 'center' of undefined at Sphere.copy (thr ...

Unable to modify border color for Material-UI OutlinedInput

Having some trouble changing the border color of a v4.13 MaterialUI Outlined Input. No luck with CSS overrides. Tested multiple CSS rules targeting different elements, such as select and OutlinedInput. Here are my latest attempts. What am I missing? cons ...

Why isn't my content appearing correctly on different pages?

This ecommerce site is my very first project using React. I have created pages for Contact, Login, and more. The footer and other components display correctly on the home page, but when navigating to other pages, the content appears shortened. For referen ...

Is it sufficient to only capture 4xx errors?

Is it necessary to catch both 4xx and 5xx errors, or is catching just 4xx errors sufficient? In regular testing of my code, when would a 5xx error even occur? ...

Tips for implementing a minimum character length feature in React Material-UI's Autocomplete feature

I am looking to add a 'minimum character length' feature to the autocomplete component in react material-ui. The code snippet below demonstrates what I have so far. constructor(props) { super(props); this.state = { // toggle for ma ...

Before the custom font finishes loading, useEffect is triggered

Custom font usage in my app: @font-face { font-family: "Koulen"; src: url("./assets/fonts/Koulen-Regular.ttf") format("truetype"); } body { font-family: "Koulen"; } An issue arises as the useEffect is called ...

"Returning undefined: The outcome of using jQuery's .html() method on

I am having an issue with the JavaScript function I have created to load content from another URL into the current document. For some reason, both contentHtml and menuHtml variables are showing as undefined. Can someone please help me identify where I we ...

Launch a new tab within the parent window, passing on variables from the parent window

Currently, I have a button that opens a new window in a new tab by using window.open("newpage.html"). In the child window, I use childVar = window.opener.parentGlobalVar to access global variables from the parent window. Now, I have been requested to open ...