Google Translate javascript snippet not working

我与影子孤独终老i 提交于 2021-02-10 16:41:52

问题


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

回答1:


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> 



回答2:


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 (i.e. on your machine), but instead will look for it on the internet.



来源:https://stackoverflow.com/questions/57401775/google-translate-javascript-snippet-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!