2016-08-09 61 views
1

Ich habe Probleme für eine HTTP-Anfrage mit chrome.runtime.sendMessage (in meinem Content-Skript) und chrome.runtime.onMessage.addListener (in meinem Hintergrund HTML-Seite).Chrome-Erweiterung: chrome.runtime.sendMessage und XMLHttpRequest();

Das Problem hier ist, dass http resquest nicht gemacht wird und ich erhalte nie Rückruf responseText richtig, kommt immer als undefined in chrome.runtime.sendMessage.

Also, ich möchte jede Hilfe für versuchen, dies zu lösen.

Hier ist mein Code:

Inhalt Skript

chrome.runtime.sendMessage({ 
    method: "GET", 
    action: "xhttp", 
    url: "http://www.example.net/echo.php?getecho", 
    data: "" 
}, function(responseText) { 
    alert(responseText); 

}); 

Hintergrund Seite html

<!DOCTYPE html> 
<html style=''> 
<head> 
chrome.runtime.onMessage.addListener(function(request, sender, callback) { 
    if (request.action == "xhttp") { 
     var xhttp = new XMLHttpRequest(); 
     var method = request.method ? request.method.toUpperCase() : 'GET'; 

     xhttp.onload = function() { 
      callback(xhttp.responseText); 
     }; 
     xhttp.onerror = function() { 

      callback(); 
     }; 
     xhttp.open(method, request.url, true); 
     if (method == 'POST') { 
      xhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); 
     } 
     xhttp.send(request.data); 

     return true; 
    } 
}); 
</script> 
</head> 
<body> 
</body> 
</html> 

PHP-Skript

<?php 
if (isset($_GET["getecho"])) 
{  
    echo "Hello i'm php script!"; 
} 
?> 

Manifest-Datei

{ 
    "background": { 

     "page": "popup.html", 
     "persistent": true 
    }, 

"description": "Foo example", 
    "manifest_version": 2, 
    "name": "Foo", 
    "icons": { 
    "128" : "picture/wmp128.png", 
    "48" : "picture/wmp48.png" 
}, 

"web_accessible_resources": [ 

    "popup.js" 
], 

"content_scripts": [ 

{ 

    "matches": ["<all_urls>", "*://*/*", "http://*/*", "https://*/*"], 
    "js": ["popup.js"], 
    "run_at": "document_end", 
    "all_frames": true 
} 

], 

    "permissions": [ "tabs", "background", "activeTab", "<all_urls>", "webNavigation", "webRequest", "http://*/*", "https://*/*", "*://*/*" ], 
    "version": "2.0" 
} 
+2

HTML-eingebetteter Code ist in Chrome-Erweiterungen nicht zulässig. Verwenden Sie anstelle von background.html eine js-Skriptdatei ([siehe Dokumentation] (https://developer.chrome.com/extensions/event_pages#manifest)). – wOxxOm

+0

@wOxxOm, gelöst! vielen Dank. –

+0

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch –

Antwort

0

Ich bin nicht ganz sicher, aber es könnte ein Sync gegen async Problem sein. This erklärt den Unterschied zwischen den beiden. Es kann einen Versuch wert sein.