简体   繁体   中英

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.

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.

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.

I tried to uninstall chrome, restart and then install it again but with no luck.

I have also allowed --allow-file-access-from-files

UPDATE 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

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

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

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

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

  ],

This permission "*://*/*", is not valid. You must specify a protocol (http or 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.

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.

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.

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. The sendMessage function's callback will be invoked automatically if no handlers return true or if the sendResponse callback is garbage-collected.

For more information on how to send requests and to setup event listener, you may want to check Message Passing .

XMLHttpRequest does not work in background scripts since a background script is a service worker:

See related: https://stackoverflow.com/a/37114241/6942857

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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