简体   繁体   English

XMLHTTPREQUEST chrome 扩展不起作用

[英]XMLHTTPREQUEST chrome extension not working

I am unable to send data from Chrome extension background script using XMLHTTPREQUEST , I have up and running wampserver, I also tried external links such as google.我无法使用 XMLHTTPREQUEST 从 Chrome 扩展后台脚本发送数据,我已经启动并运行 wampserver,我还尝试了外部链接,例如 google。

What does it do :它有什么作用 :

User enters a permission defined tab, background script waits for hot key,when pressed a content_script is launched and generates a string, the string is sent back to the background script, then the background script should receive the string and send it to a php file, the php file should print hello, its made simple just to try see where is the problem, later php will have more code.用户输入权限定义选项卡,后台脚本等待热键,按下时启动 content_script 并生成一个字符串,将字符串发送回后台脚本,然后后台脚本应接收该字符串并将其发送到 php 文件, php 文件应该打印 hello, 简单试一下看看是哪里出了问题,后面的 php 会有更多的代码。

But its completely not working!但它完全不起作用!

UPDATE更新

I tried to pack the extension then run it by drag and drop, it doesn't launch php script.我试图打包扩展然后通过拖放运行它,它不会启动 php 脚本。

I tried to uninstall chrome, restart and then install it again but with no luck.我试图卸载 chrome,重新启动,然后再次安装,但没有运气。

I have also allowed --allow-file-access-from-files我还允许--allow-file-access-from-files

UPDATE 2更新 2

I am receiving the following error in debug mode:我在调试模式下收到以下错误:

extensions::sendRequest:41: Uncaught TypeError: Cannot read property 'callback' of undefined{TypeError: Cannot read property 'callback' of undefined扩展::发送请求:41:未捕获的类型错误:无法读取未定义的属性“回调”{TypeError:无法读取未定义的属性“回调”

Manifest.json清单文件

{

  "manifest_version": 2,
  "name": "Extractor",
  "version": "1",


  "description": "Extract from 144",
  "icons": { "16": "logo16.png",
           "48": "logo48.png",
          "128": "logo128.png" },


        "page_action": {
          "default_icon": {                    
            "16": "logo16.png",           
            "48": "logo48.png",           
            "128": "logo128.png"            
          },
          "default_title": "Extractor"          
        },

  "background": {

    "scripts": ["background.js"],
    "persistent": true
  },
  "content_scripts": [
    {
      "matches" : ["https://www.msn.com/*"],
      "js" : ["content_script.js"]
    }
  ],
 "permissions": [
    "tabs",
    "https://www.msn.com/*",
    "activeTab",
     "http://localhost/*"

  ],
  "commands": {
           "toggle-feature": {
            "suggested_key": {
              "default": "Ctrl+Shift+1",
              "windows": "Ctrl+Shift+2"
            },

            "description": "Extract now"
          }
        } ,
"web_accessible_resources": ["content_script.js"]

}

Background.js背景.js

chrome.commands.onCommand.addListener(function(command) {
 if (command === "toggle-feature") { 
 chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
     for(var i = 0; i<tabs.length;i++) {
           chrome.tabs.executeScript(tabs[i].id, {"file": "content_script.js"});
     }
   });
  }
}); 

chrome.runtime.onMessage.addListener(
  function(message, sender, sendResponse) {

    var xhttp = new XMLHttpRequest();
    xhttp.open("POST", "http://localhost/test/test.php");
    xhttp.send(message.url);

  });

content_script.js content_script.js

var url = 'this is just test' ;
chrome.runtime.sendMessage({ 'url' : url });

test.php测试文件

echo "hello";

You only able to make XHR Request from chrome extension to URL you defined in your manifest.json in your code, you should add http://localhost to your manifest.json 您只能从chrome扩展名向代码中manifest.json中定义的URL发出XHR请求,您应该将http://localhost添加到manifest.json

 "permissions": [
    "tabs",
    "https://www.msn.com/*",
    "activeTab",
     "*://*/*",
     "http://localhost/"

  ],

This permission "*://*/*", is not valid. 此权限"*://*/*",无效。 You must specify a protocol (http or https) 您必须指定协议(http或https)


More Info: 更多信息:

You may want to check in your code if there's chrome.extension.sendRequest which was already depracated since Chrome 33. Please use runtime.sendMessage instead. 您可能想检查一下您的代码是否存在自Chrome 33以来已被废弃的chrome.extension.sendRequest 。请改用runtime.sendMessage

In addition to that, Simple one-time requests states that, if you only need to send a single message to another part of your extension (and optionally get a response back), you should use the simplified runtime.sendMessage or tabs.sendMessage. 除此之外,“ 简单一次性请求”指出,如果只需要向扩展的另一部分发送一条消息(并有选择地返回响应),则应使用简化的runtime.sendMessage或tabs.sendMessage。

And, sending a request from a content script looks like this: 并且,从内容脚本发送请求看起来像这样:

chrome.runtime.sendMessage({greeting: "hello"}, function(response) {
  console.log(response.farewell);
});

On the receiving end, you need to set up a runtime.onMessage event listener to handle the message. 在接收端,您需要设置runtime.onMessage事件侦听器以处理消息。

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    console.log(sender.tab ?
                "from a content script:" + sender.tab.url :
                "from the extension");
    if (request.greeting == "hello")
      sendResponse({farewell: "goodbye"});
  });

Furthermore, it was noted that: 此外,据指出:

The sendResponse callback is only valid if used synchronously, or if the event handler returns true to indicate that it will respond asynchronously. sendResponse回调仅在同步使用或事件处理程序返回true表示将异步响应时才有效。 The sendMessage function's callback will be invoked automatically if no handlers return true or if the sendResponse callback is garbage-collected. 如果没有处理程序返回true或sendResponse回调被垃圾回收,则sendMessage函数的回调将被自动调用。

For more information on how to send requests and to setup event listener, you may want to check Message Passing . 有关如何发送请求和设置事件侦听器的更多信息,您可能需要检查Message Passing

XMLHttpRequest does not work in background scripts since a background script is a service worker: XMLHttpRequest在后台脚本中不起作用,因为后台脚本是一个服务工作者:

See related: https://stackoverflow.com/a/37114241/6942857相关见: https : //stackoverflow.com/a/37114241/6942857

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM