It is not possible to include external JavaScript in a Vue.js web page

Trying to integrate a Google Translate widget onto my webpage has been a bit challenging. Initially, when I added it to a normal webpage, it worked smoothly using the following code:

<div class="google_translate" id="google_translate_element"></div>

<script type="text/javascript" src="https://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>

function googleTranslateElementInit() {
  new google.translate.TranslateElement({
    pageLanguage: 'en'
  }, 'google_translate_element');
}

However, when I tried moving this setup to my VueJs project, it no longer functioned correctly. I suspected that the external script might be the issue, so I attempted to create a local JavaScript file and link it to my page, but encountered more problems. Can someone point out where I am going wrong here? My application is built using VueJS and webpack.

Within my VueJS page, I placed the googleTranslateElementInit function inside the mounted() block and continued calling the external scripts as I did on the normal page.

mounted () {

setTimeout(function (){ 
  $('.article-list').masonry({
    columnWidth: 208,
    itemSelector: '.article-box',
    fitWidth: true
  });
},0)
$("#menu-pagetop").on("click", function () {
  $('body,html').animate({
    scrollTop: 0
  }, 800);
  return false;
});
window.onscroll = function () {
  scrollFunction()
};

function scrollFunction() {
  if (document.body.scrollTop > $("#menu").offset().top || document.documentElement.scrollTop > $("#menu").offset().top) {
    $("#menu-pagetop").is(".shown") || $("#menu-pagetop").stop().fadeIn(180).addClass("shown")
  } else {
    $("#menu-pagetop").is(".shown") && $("#menu-pagetop").stop().fadeOut(180).removeClass("shown");
  }
}
function googleTranslateElementInit() {
  new google.translate.TranslateElement({
    pageLanguage: 'en'
  }, 'google_translate_element');
}
}

Answer №1

To ensure that the google translate widget functions properly, you need to make the googleTranslateElementInit function accessible within scope. You can achieve this by implementing the following code snippet:

mounted () {
  window.googleTranslateElementInit = function () {
    new google.translate.TranslateElement({pageLanguage: 'en', layout: google.translate.TranslateElement.InlineLayout.SIMPLE}, 'google_translate_element');
  }
},

The provided sample snippet may display some cross-origin errors but should work fine on a local environment.

new Vue({
  el: '#example',
  mounted () {
    window.googleTranslateElementInit = function () {
      new google.translate.TranslateElement({pageLanguage: 'en', layout: google.translate.TranslateElement.InlineLayout.SIMPLE}, 'google_translate_element');
    }
  }
})
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.10/dist/vue.js"></script>
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no">
    <title>Example</title>
    <script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
  </head>
  <body>
    <div id="example">
      <div id="google_translate_element"></div>
    </div>

  </body>
</html>

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

AngularJS RESTful Routing Masterclass

I am in the process of organizing my application using the Restful/Ruby convention /<resource>/[method]/[id]. In the past, when working with a server-side MVC framework like CodeIgniter, I would dynamically route based on the URI: For example: www. ...

Transform shapefiles to geojson format using OpenLayers 5

As I embark on a new project that involves combining Vue.js and OpenLayers, I am thoroughly enjoying the process. While I have successfully implemented various functionalities like drawing, reading, and modifying vectors, I find myself stuck when it comes ...

Providing Node-server with Vue.js Server Side Rendering

I've been attempting to deploy the Hackernews 2.0 demo on my Digital Ocean droplet but have hit a roadblock. npm run start starts the server on port :8080. npm run build is used for production builds. The specific build tasks can be found below: ...

The image source failed to load the image using the function

Initially, I set up a sandbox to work on this issue: https://codesandbox.io/s/naughty-almeida-u66mlt?file=/src/App.js The main problem arises when the requested image fails to display after the function is called and the URL is returned. Here are my atte ...

Angular Bootstrap: How to Resolve the Error "Function $(...).collapse() is Undefined"

I'm a beginner with Bootstrap and I'm attempting to trigger the .collapse() function using JavaScript within an Angular controller when a user clicks on a link. The goal is to close the collapsible navbar when a link is clicked, as the routing in ...

Is there a way to identify and count duplicate data-items within an array, and then showcase this information using a react view?

If we have an array like this: [{id: 1, name: "chocolate bar"}, {id:2, name: "Gummy worms"}, {id:3, name:"chocolate bar"}] Is there a way to show on the dom that we have "2 chocolate bars and 1 Gummy Worms"? ...

Guide on extracting the ID within a for loop and incorporating it into a Vue.js function

In order to make an API request, I need to retrieve the id. However, whenever I try to include <a v-on:click="showRecipe({{inf.Id}})">Recipe</a> in my code, the entire page crashes. Removing this line resolves the issue. How can I pass the id ...

PHP and AJAX allow for seamless data retrieval without the need for page refreshing, and the data can be easily displayed in a modal window

I am currently encountering an issue with sending data to another page without refreshing. I am able to send the data as text, but for some reason, I am unable to send it as a modal. Why might this be happening? Here is an image of my current page https:/ ...

Troubleshooting the non-functioning addEventListener in JavaScript

I am facing an issue where a function that should be triggered by a click event is not working and the console.log message does not appear <script src="e-com.js" async></script> This is how I included the javascript file in the head ...

Tips on verifying the existence of a file in Nuxt

Currently working with Nuxt version 2.15.4 and I am looking to verify within my store code whether a file exists in the Nuxt directory using the fs-extra package. It's straightforward when dealing with modules because I can obtain the file path utili ...

What is the most effective method for displaying an error code when a JavaScript error occurs?

I'm currently dealing with a library that is throwing errors: throw new Error('The connection timed out waiting for a response') This library has the potential to throw errors for various reasons, making it challenging for users to handle ...

The issue with 'DemoCtrl' defined in Angular JS is that it does not correspond to a valid argument

signup.html <div ng-controller="UniqueCtrl" layout="column" ng-cloak="" class="md-inline-form inputdemoBasicUsage" ng-app="inputBasicDemo"> <md-content md-theme="docs-dark" layout-gt-sm="row" layout-padding=""> <div> <md- ...

Performing Batch Writes in Firestore using the Admin SDK

I have a massive ASCII flat file containing 1.5 million lines, which is essentially a list of parts from a manufacturer. I want to store this data in Firestore. Originally saved as a .csv file, the size was 250GB. After converting it to a JSON file using ...

Enhance CSS delivery for the items listed below

Reduce the delay caused by rendering JavaScript and CSS above-the-fold. There are 16 CSS resources currently blocking the rendering of your page. This delay could be affecting the loading time of your content. To improve this issue, consider deferring or ...

TypeError thrown by Mapbox markers

Looking to incorporate markers into my map using Mapbox. Below is the Angular TypeScript code I am working with: export class MappViewComponent implements OnInit { map: mapboxgl.Map; lat = 41.1293; lng = -8.4464; style = "mapbox://styles/mapb ...

What is the process for extracting components from a JSON file using an observable in Angular?

Take a look at this snippet of code: response: any; fetchData(url: any) { this.response = this.http.get(url); } ngOnInit(): void { fetchData("url.com/data.json"); console.log(this.response) } When I check the console, I see Obser ...

Increment and decrement the like count on fa-heart multiple times

Is there a way to increment the count of a fa-heart value on click and decrement it on the second click? The issue I'm facing is that I have multiple fa-heart elements on the same page, making it challenging to increment or decrement the clicked fa-h ...

What is causing the click event handler to only function on the initial page?

Within my code for the "fnInitComplete" : function(oSettings, json), I am utilizing a selector like $('[id^=f_]').each(function (). The data for Datatables is retrieved server-side and "bProcessing":true I am aware that my selectors are only ef ...

What is the functionality of this JavaScript code after the "if" statement?

I am having trouble understanding how this code works, especially after the if(y in hash) statement. I don't see any values being pushed into hash initially. Can someone explain what happens behind the scenes and the significance of y in hash? var ...

Incorporating External JavaScript and CSS specifically for a single component

In my Angular 4 application, I have a specific component that requires the use of a js and css file. While most guidelines suggest placing these files in the Index.html file, I prefer to only load them when this particular component is accessed, not on e ...