crossOrigin blocks requests for translate.google.com

31 Views Asked by At

I am trying to develop an extension which uses tts media fetched from https://translate.google.com/translate_tts API endpoint. When I use audio.crossOrigin = "anonymous";, I get the following error:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://translate.google.com/translate_tts?client=tw-ob&tl=en-US&q=hello. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 200

My code:

function tts(flag_id, lang) {
  document.getElementById(flag_id).addEventListener('click', () => {
    let query = document.getElementById('search-input').value;
    let source = `https://translate.google.com/translate_tts?client=tw-ob&tl=${lang}&q=${query}`;
    let audio = new Audio(source);
    audio.crossOrigin = "anonymous";
    audio.load();
    audio.play();
  });
}

My manifest file:

{
   "author": "*",
   "manifest_version": 3,
   "name": "*",
   "short_name": "*",
   "description": "*",
   "version": "7.1.1",
   "action": {
      "default_icon": {
         "128": "images/AppIcon.png",
         "256": "images/AppIcon.png"
      },
      "default_popup": "popup.html",
      "default_title": "*"
   },
   "host_permissions": [
      "https://*.google.com/*"
   ],
   "icons": {
      "128": "images/AppIcon.png",
      "16": "images/AppIcon.png",
      "256": "images/AppIcon.png"
   },
   "permissions": [
      "<all_urls>",
      "activeTab",
      "contextMenus",
      "scripting"
   ],
   "background": {
      "scripts": [
         "scripts/background.js"
      ]
   },
   "options_ui": {
      "page": "info.html"
   },
   "commands": {
      "_execute_action": {
         "suggested_key": {
            "chromeos": "Ctrl+Alt+V",
            "default": "Ctrl+Alt+V",
            "linux": "Ctrl+Alt+V",
            "mac": "Ctrl+Alt+V",
            "windows": "Ctrl+Alt+V"
         }
      }
   },
   "omnibox": {
      "keyword": "ms"
   }
}

The first idea I had was that the google servers don't process the requests originating from my extension since my extension is not registered in Access-Control-Allow-Origin in the google API servers. Then I checked the simple-translate extension, which has the following script:

const playAudio = async (text, lang) => {
  const url = `https://translate.google.com/translate_tts?client=tw-ob&q=${encodeURIComponent(
    text
  )}&tl=${lang}`;
  const audio = new Audio(url);
  audio.crossOrigin = "anonymous";
  audio.load();
  await audio.play().catch(e => log.error(logDir, "playAudio()", e, url));
};

Unlike my extension, simple-translate extension doesn't get Cross-Origin Request Blocked error. What might be the issue?

0

There are 0 best solutions below