简体   繁体   中英

XMLHttpRequest error with Google translate (No 'Access-Control-Allow-Origin' header)

I am getting this error while trying to access a page that uses Google Translate :

XMLHttpRequest cannot load http://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit . No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin ' http://localhost:8080 ' is therefore not allowed access.

I have read multiple posts about this problem here on SO but I haven't found a way to make it work with the way we initialize the Google Translate gadget.

The solutions that are proposed include setting the dataType to jsonp and adding Access-Control-Allow-Origin: * to the header of the XMLHttpRequest . However, I am not doing an AJAX call like the ones in the other posts, only initializing the Google Translate element with a script provided by Google :

<script type="text/javascript">
          function googleTranslateElementInit() {
                new google.translate.TranslateElement({pageLanguage: 'en',
                    layout: google.translate.TranslateElement.InlineLayout.SIMPLE,
                    includedLanguages: 'fr,en'
                }, 'hiddenGoogleTranslate');
</script>
<script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>

How can I define the dataType or add something to the header with this initialization script ? I am new to Javascript so there must be something I am missing out.

Thank you!

alternatively, you can use curl or file_get_content() (webproxy) at your server to get translated text. Then you can access that url with ajax. if you want to define "Access control allow origin" header to * you can do it at your server (not from js). your url can be accessed cross domain.

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