Is it possible to refresh AdSense banner when the router changes?

Is there a way to reload the AdSense banner ads when the router changes? I've been encountering issues trying to re-add the script and HTML properly. Any guidance on how this should be done would be greatly appreciated...


This is just a test for one of the proposed solutions.

Edit:

<div v-if="ads" class="ads"><ins v-if="adsense" :key="id" class="adsbygoogle" style="display: inline-block; width: 320px; height: 50px;" data-ad-client="ca-pub-XXX" data-ad-slot="XXX"></ins></div>
...
data () {
  return {
    device: {},
    ads: false,
    adsense: false,
    id: 1
  }
}
...
methods: {
  AdSense: function () {
    (window.adsbygoogle = window.adsbygoogle || []).push({})
  }
}
...
mounted: async function () {
  let adsense = document.createElement('script')

  adsense.setAttribute('data-ad-client', 'ca-pub-XXX')
  adsense.setAttribute('async', '')
  adsense.setAttribute('src', 'https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js')

  document.head.appendChild(adsense)

  this.ads = true

  this.adsense = true

  this.AdSense()
}
...
watch: {
  $route (to, from) {
    if (to !== from && to.name !== 'authorize' && this.device.platform === 'web') {
      this.id++
    }
  }
}

Answer №1

Each time the AdSense method is called, it attempts to add another script tag to the document's head. The error indicates that the Google ads script should only be included once.

To resolve this issue, you should separate the script tag creation into its own method and ensure it is only invoked once.

Additionally, for refreshing the ad element, consider adding a key attribute. When you need to reload the ads, increment the key value to trigger a re-render.

<ins v-if="adsense" class="adsbygoogle" :key="id"></ins>
data() {
    return {
        id: 1;
    }
},
watch: {
    $route (to, from) {
        if(to !== from) { 
            this.id++;
        }
    }
}

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 form data is being passed as null to HttpContext.Current.Request

My file upload module is working well with Postman without any content type. However, in the code, the file count always shows as 0 in the backend API. If anyone has any insights into what I might be doing wrong, please help me out. Thank you. Below is my ...

Passing a variable between pages in PHP: a simple guide

In my *book_order* page, I allow users to input orders into a table called *order_management*. The order_id is auto-incremented in this table. After submitting the page, I need to pass the order_id to another page named *book_order2* where products can be ...

Vue.js - acquire fresh data insights

Working on a chrome extension with vue.js, I aim to display tab information in my template. Here is the code snippet: <template> <div> <p>{{ tab.url }}</p> </div> </template> <script> export default { d ...

Is it advisable to perform several Firestore queries within a single cloud function to minimize round-trip times?

Exploration Within my application scenario, I have a specific screen that displays 8 different lists of items. Each list requires a separate query to Firestore, running asynchronously to retrieve documents from various collections. Through profiling the e ...

I am eager to utilize emit in order to toggle between various page components

I currently have a Header and a Main page displayed on the Top page, along with three Tab functions in the Header component. My goal is to switch between displays A, B, and C on the Main page when I click on each corresponding Tab (A, B, C). I've been ...

How do you modify the SVG viewport using code?

I am looking to create a feature that allows all images inside an SVG object to be moved. My plan is to use JavaScript, and possibly jQuery, to handle mouse events (down, move, up) in order to change the viewport of the SVG. However, I am currently facing ...

Moving from the end to the beginning with a jQuery slider transition

Instead of relying on external plugins, I built this slider from scratch: function customSlider(selector, interval, index) { var slider = this; this.ind = index; this.selector = selector; this.slides = []; this.activeSlide = 0; this.amount; ...

JavaScript's setTimeout function seems to be executing an excessive number of times

After creating a loop with the setTimeout function, I encountered an issue where it would call itself after the 2nd or 3rd step because it started executing twice simultaneously. Here is how my function looks: var value = 70, intervalID = null; func ...

Determining the file size of an HTML and JavaScript webpage using JavaScript

Is there a way to determine the amount of bytes downloaded by the browser on an HTML+JS+CSS page with a set size during page load? I am looking for this information in order to display a meaningful progress bar to the user, where the progress advances bas ...

Generate interactive tables using data from an XML file

Hello, I'm in the process of generating tables from an XML file using Node.js with the Express framework. I am utilizing npm modules xmldom and xmldoc for this task. The objective is to present these data tables on an ejs page. Here is the structure ...

What strategies can I use to refactor this controller in Angular 1.5 to make it more concise and efficient

I am encountering an issue with a component I have that contains a button. Whenever the button is clicked, it triggers one of two backend services depending on where the component is located. To achieve this, I am currently passing a flag to the component ...

Dealing with useEffect being invoked twice within strictMode for processes that should only execute once

React's useEffect function is being called twice in strict mode, causing issues that need to be addressed. Specifically, how can we ensure that certain effects are only run once? This dilemma has arisen in a next.js environment, where it is essential ...

The Link tag in the Hero.jsx file of Next.js is malfunctioning and failing to redirect to the intended URL

Having a problem with the button in my Hero.jsx component, part of the Page.js implementation. The button uses a Link tag to redirect to the url.js page, but it's not working as expected and showing an Error 404 page instead. I'm new to Next.js s ...

What is the process for loading Syntax Highlighter on pages with pre tags?

As a Blogger, I often find myself in need of demonstrating codes on my blog. To achieve this, I have been using a Syntax Highlighter developed by Alex Gorbatchev. However, a recurring issue I face is that the files load on every single page of my blog, cau ...

Creating a React component dynamically and applying unique custom properties

I'm currently in the process of refactoring my React code to enhance its usability in situations where direct use of Babel is not possible, such as in short snippets of JavaScript embedded on web pages. As part of this refactor, I am setting up a conc ...

Allow the words to seamlessly transition back and forth between columns in a continuous cycle

Currently, I am attempting to showcase a large text in a format similar to a book. Each "page" has designated width and height, with content displayed over two columns: left and right. In this layout, page 1 is on the left, page 2 on the right, page 3 on t ...

finding and retrieving every occurrence of the select directive and its corresponding selected values in Angular

I recently set up a chosen dropdown in my project using the following method. I added a select box with a "chosen" directive as an attribute to update and initialize a list, along with an ng-model on the select element. <select id="{{$index+1}}" class= ...

Is there a way to segment a string into words using a dictionary and finding the longest match in JS/Jquery?

Imagine you have a string like this: var str = "thisisinsane"; and a list of words from a dictionary such as: var dic = [ "insane", "i", "is", "sin", "in", "this", "totally" ]; How can we separate the words in str? In this specific case, there a ...

What is the reason for IE displaying null when the model does not exist?

Why does IE 11 render 'null' if my model does not exist? For instance: <tr> <td [innerHTML]="model?.prop1 | my-pipe"></td> </tr> Imagine this scenario: When the page loads, a request is sent to the server and the res ...

When the component mounts in React using firestore and Redux, the onClick event is triggered instantly

I am facing an issue with my component that displays projects. Each project has a delete button, but for some reason, all delete buttons are being automatically triggered. I am using Redux and Firestore in my application. This behavior might be related to ...