0

This is my first question on Stack Overflow. I’m new to chrome extensions and javascript in general. I'm currently working on a chrome extension that translates a user selected word from French to English.

When the user clicks a button, a message is sent from popup.js to content.js, which then listens out for a mouseup event to get user selected word. A message is then sent to background.js, which takes the user selected word, and sends a post request to the Microsoft Translator API to translate it to English.

However, when I run the extension, I keep getting a 405000 error on the API which means that the request method is not supported for the requested resource. I've spent all of yesterday trying to figure out what is going on, and so far I'm stumped. I'm 1000% certain that a POST method is required for this, and that my URL is correct. I'm using fetch API for the request.

I've included my code below. None of the questions previously posted on here have helped me. Would someone be able to point out where I may have gone wrong? Many thanks in advance.

CODE

Manifest.json

{
  "name": "Translate Extension",

 "version": "1.0",
 
"description": "French Translation",
 
"manifest_version": 2,

 "browser_action": {
   "default_icon": "icon.png",
   "default_popup": "popup.html"
 },

 "permissions": ["activeTab", "tabs", "https://api-eur.cognitive.microsofttranslator.com/"],

 "content_scripts": [
   {
    "matches": ["<all_urls>"],
    "js": ["contentScript.js"]
   }
 ],

 "background": {
   "scripts": ["background.js"],
   "persistent": false
 }

}

Popup.js

document.getElementById("myBtn").addEventListener('click', () => {
   
   chrome.tabs.query({active: true, currentWindow: true}, function(tabs) { 
     
      chrome.tabs.sendMessage(tabs[0].id, {action: 'getWord'}, response => {
         console.log(response);
    });
 
 });

});

Content.js

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  
if (request.action === 'getWord'){
       
         window.addEventListener("mouseup", function()
        {
        
           var text = window.getSelection();
         
           var txt = { Text: text };
         
           var t = JSON.stringify(txt);
        
           chrome.runtime.sendMessage(
          {
            contentScriptQuery: "getFrench"
            , data: t
            , url: "https://api-eur.cognitive.microsofttranslator.com/translate?api-version=3.0&from=fr&to=en"
          }, function (response){
              debugger;
         });
           sendResponse('done!');
        });
   
   }
    sendResponse('done!');
   return true;
});

Background.js

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
  
if(request.contentScriptQuery == "getFrench"){
     
     fetch(request.url, {
        method: "POST",
        headers: {
           'Content-Type': 'application/json; charset=UTF-8',
           'Content-Length': Object.keys(request.data).length,
           'Ocp-Apim-Subscription-Key': 'f2e7a795d2074279a7b59ba23aede0e3',
           'Ocp-Apim-Subscription-Region': 'westeurope',
           'Accept': 'application/json' },
        body: request.data
      })
        .then(response => response.json())
        .then(response => sendResponse(response))
        .catch(error => console.log('Error:', error));
      return true;
      
    }
     sendResponse({
        response: "Message received"
    });
   
 });
       
  • 1. You need to add the site to `permissions`, see also the [documentation](https://developer.chrome.com/docs/extensions/mv2/xhr/). 2. Your onMessage is missing `return true` at the end, [example](https://stackoverflow.com/a/55292071). – wOxxOm Mar 13 '21 at 05:23
  • @wOxxOm I did as you said, (appropriate edits made to above code also) yet it still gives the 405000 error. Have I done something wrong? – Cornelius Hickey Mar 25 '21 at 20:23
  • Maybe the remote server rejects extensions. You can try using chrome.webRequest.onBeforeRequest (with `extraHeaders` mode) to change such headers (probably `Origin`). – wOxxOm Mar 26 '21 at 03:49

0 Answers0