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

jQuery toggle functioning in one scenario, but failing in another

My experience with JS/Jquery is limited which might explain why I'm struggling with this. I am attempting to hide some text on a page and then make it visible again by clicking on a toggle link. The JavaScript code below is what I have been using. The ...

There seems to be an issue with the functionality of the Bootstrap Modal

I've been working on incorporating bootstrap login Modal functionality into my code, but for some reason, the screen is not displaying it. Here's what shows up on the screen: The red box in the image indicates where I am expecting my Login Modal ...

Track the number of books read per month using an array of objects

Consider the following array of objects: const sampleArray = [{"read":true,"readDate":2021-01-15T18:21:34.059Z}, {"read":true,"readDate":2021-01-15T18:21:34.059Z}, {"rea ...

What is the best way to add JSON data to a table?

I have developed a php script to create json data. However, I am facing an issue while trying to display this generated json data in a table. While my php code successfully generates the data, it is unable to insert it into the table. I would appreciate an ...

Converting data to JSON geometry format for implementation in Three.js

Currently, I am in the process of creating an exporter using Maxscript to convert data into JSON format for use in Three.js. Information on this topic is scarce, but I did come across a helpful resource: https://github.com/mrdoob/three.js/wiki/JSON-Geometr ...

What is preventing me from using memoization in the getServerSideProps of NextJS?

I'm currently using React along with NextJS to showcase a variety of products on a specific category page. While I am able to successfully fetch the products utilizing getServerSideProps, I am not fond of how it continuously requests the product cata ...

"Could you please help me understand the process of receiving a JSON in an Express

When working with React, I encountered an issue where the JSON data sent to me from the front-end is in a strange format (an object with the data as a string). I am unsure how to convert it back into the object type. This is what I send: const data = { ...

The operation of 'val' is not supported by HTMLInputElement

While working with a table row, I am iterating through each cell. Inside every cell lies a text box containing some value that I need to store in an array. function dothing() { var tds = $('#'+selected+' td'); var submi ...

The JavaScript code is not executing properly within the HTML document

I am trying to execute a function from my JavaScript file in my HTML page. Here is the code snippet: index.html <!DOCTYPE html> <html><body> <h2>Web1</h2> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jq ...

Vue Custom Element encountering issues when generating independent JavaScript files in the Dist directory

I recently followed the instructions for registering and utilizing custom elements as outlined here: https://alligator.io/vuejs/custom-elements/ For my project, I am using the standard Webpack template for Vue. After executing the command npm run buil ...

What is the appropriate overload to be selected when utilizing a ref in the method call?

Encountering an unfamiliar TS error while working with the code snippet below: <script lang="ts"> import {defineComponent, computed, toRef} from 'vue' import _ from 'lodash' import {DateTime} from 'luxon' int ...

Locate an array within a Multidimensional array and relocate it to the starting position

I've been attempting to figure out a solution for moving a specific array within another array to the beginning. The problem I'm encountering is that the code I was using, as suggested in a previous question, only removes the last value and plac ...

Challenges of aligning a modal overlay in the middle of mobile screens

Currently, I am developing a website and encountering a specific issue with the modal structure. When viewing it on Codepen using Chrome devtools and toggling the device toolbar to simulate mobile screens, everything appears fine. However, when opening the ...

Working with JavaScript and making AJAX calls to interact with PHP backend

Having trouble with this code, it's not working as expected. I want to pass the value when I select an option from the dropdown menu, process the data using onChange event and display the value in the tag. <label for="headmark" class="lbl-ui selec ...

Patience is key when waiting for Ajax response data in Vue.js

Within my Vue component, I am attempting to retrieve data from an API using axios. <template> <div> This is Default child component {{tools[0].name}} </div> </template> <script> import { CustomJS } fr ...

Having trouble retrieving information from the JSON data received from the Google Place Search API

I'm encountering an issue with accessing data from the Google Place Search API. I've provided my code below for reference. getData = (keyword, location, country) => { let dataURI = `${URI}${keyword}+${location}+${country}${API}`; var ...

Passing an ID via Link to retrieve data with getServerSideProps in Next.js

I have several alert components. From each of these components, I aim to pass the itm._id and receive it in [itm].jsx within the same folder. In [itm].jsx, I intend to utilize it in the getServerSideProps function for fetching data. Below is a snippet fro ...

Enforce a restriction on the user's input value for the amount field within a React application

I'm looking to limit the user from entering more than 50000 in the input value. How can I achieve this using React? I am currently handling this on the onchange event. onPaymentAmountChanged = (e) => { let inputValue = e.target.value; if (i ...

Why isn't the Full Calendar loading automatically within a Bootstrap Tab?

I have been working on a travel website and incorporated a bootstrap tab feature. In the first tab, I have some content, while in the second tab, I've added a full calendar with JavaScript. Everything seems to be functioning correctly when the full ca ...

Combining Multiple Arrays into One | Node.js

Can someone explain how to merge an array of arrays to me? For instance, I have the following array: [ [ {brand: 'fiat', model: 'palio'} ], [ {brand: 'nissan', model: 'march'} ] ] I want to transform this array int ...