如何解决Google Chrome 扩展中的 Microsoft Translate API 错误 405000
这是我关于 Stack Overflow 的第一个问题。我是 chrome 扩展和 javascript 的新手。我目前正在开发一个 chrome 扩展程序,可将用户选择的单词从法语翻译成英语。
当用户点击一个按钮时,一条消息从 popup.js 发送到 content.js,然后它监听 mouseup 事件来获取用户选择的单词。然后将一条消息发送到 background.js,它接受用户选择的单词,并将发布请求发送到 Microsoft Translator API 以将其翻译成英语。
但是,当我运行扩展程序时,我不断在 API 上收到 405000 错误,这意味着请求的资源不支持请求方法。我昨天一整天都在试图弄清楚发生了什么,但到目前为止我都被难住了。我 1000% 确定为此需要 POST 方法,并且我的 URL 是正确的。我正在为请求使用 fetch API。
我在下面包含了我的代码。以前在这里发布的问题都没有帮助我。有人能指出我可能出错的地方吗?非常感谢。
代码
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,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"
});
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。