Reputation: 633
I send the url to a php file in chrome extension, and need get response, but doesn't work.
manifest.json
{
"name": "Get pages source",
"version": "1.0",
"manifest_version": 2,
"description": "Get pages source from a popup",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"permissions": ["http://localhost/"]
}
popup.js
chrome.tabs.query({'active': true, 'lastFocusedWindow': true}, function (tabs) {
var url = tabs[0].url;
var parametros = {
"url" : url
};
$.ajax({
type: "POST",
data: parametros,
url: 'file.php',
success: function(data) {
var res = jQuery.parseJSON(data);
alert("success");
},
error: function(e) {
alert("error");
}
});
});
file.php - Is in the same folder, in localhost
<?php
$resultado = $_POST['url'];
echo $resultado;
?>
and the popup.html
<html style=''>
<head>
<script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
<script src='popup.js'></script>
</head>
<body style="width:400px;">
<span id="resultado">0</span>
</body>
</html>
This code only return a empty array.
Not is posible use Ajax in chrome extension?
EDIT:
I charge jquery with a local file, not CDN, and work fine.
Other issue is in my code, I thing that is in jQuery.parseJSON.
Thanks to all ;)
Upvotes: 2
Views: 4813
Reputation: 77482
Your problem is with the URL you're trying to POST to.
$.ajax({
type: "POST",
data: parametros,
url: 'file.php', // That's a relative URL!
success: function(data) {
var res = jQuery.parseJSON(data);
alert("success");
},
error: function(e) {
alert("error");
}
});
Assuming your extension's ID is aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
, then your popup will have the URL chrome-extension://aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/popup.html
, and this will result in a request to chrome-extension://aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/file.php
, not your local server that you said you're using in the comments.
You need to use the full URL:
url: 'http://localhost/file.php'
Upvotes: 3