简体   繁体   English

谷歌翻译 javascript 片段不工作

[英]Google Translate javascript snippet not working

I tried using the code snippet from w3school.com.我尝试使用 w3school.com 中的代码片段。 It worked on w3school but doesnt work on my PC.它适用于 w3school 但不适用于我的 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. w3school上的代码片段确实存在错误。 It says to add the following line to include Google's API: 它说要添加以下行以包含Google的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. 因此,除非您已下载该库并将其与html文件捆绑在一起,否则这将指向无处。 Instead link to the online library by adding https: 而是通过添加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. 因此,从//translate.google等加载的源文件正试图在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. 您会发现它不再尝试查找本地文件(即在您的计算机上),而是在Internet上寻找它。

pure javascript, can be integrated from browser debug console, or in webview, or any site.纯 javascript,可以从浏览器调试控制台、webview 或任何站点集成。 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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