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

1

6

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!

Tannin answered 11/8, 2014 at 15:59 Comment(4)
Please consider adding a downvote reason, I know there are lots of posts about this problem but I haven't found any that uses the googleTranslateElementInit script.Tannin
Can u post a jsfiddle demonstrating the issue?Cedilla
I tried it here jsfiddle.net/zznv5tet doesn't seem to throw any errors - can u build upon this sample?Cedilla
@YuriyGalanter Indeed, it works fine in your jsfiddle. The problem happens when we naviguate from one page to another, I don't know how to replicate this in a jsfiddle..!Tannin
N
0

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.

Nazario answered 5/9, 2014 at 3:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.