简体   繁体   中英

Google Translate javascript snippet not working

I tried using the code snippet from w3school.com. It worked on w3school but doesnt work on my PC.

<div id="google_translate_element"></div>
<script>

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

</script>
<script src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>

I got the following in the console.

translate.html:18 GET file://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit net::ERR_FILE_NOT_FOUND

The snippet over at w3school indeed has a bug. It says to add the following line to include Google's API:

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

Unfortunately the trailing // makes it point to a local file. So unless you've downloaded the library and bundled it with your html file this points to nowhere. Instead link to the online library by adding https:

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

When you're running it on your machine, you're running it as a local file. As such, the source file, which is loading from //translate.google etc, is trying to find this file on google.

If you replace this with:

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

you will find it is no longer trying to find a local file (ie on your machine), but instead will look for it on the internet.

pure javascript, can be integrated from browser debug console, or in webview, or any site. In this example we just find element and change his content to button (you can change any element you want)

importScriptURI("https://translate.google.com/translate_a/element.js"); 
document.getElementsByTagName("h1")[0].innerHTML='<div id="google_translate_element"></div>';
setTimeout(()=>{ new google.translate.TranslateElement({pageLanguage: 'en'},'google_translate_element');},1000);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM