I wanna to send request form a webpage to chrome extension, and then in chrome extenison receive data and read data, is there any way to this?
Ex:
In doman www.nope.com/sendRequest.html will sent data to chrome extension via url chrome-extension://xxxxxxx/getData.htm?isToken=abc, and then extension will receive and can read data "isToken".
Here is my code in sendRequest.html
<script type="text/javascript">
function sendRequest() {
document.write("Sending request");
var req = new XMLHttpRequest();
req.open("POST", "chrome-extension://xxxxxxxxxx/getData.htm?isToken=abc", true);
req.onreadystatechange = function () {
if (req.readyState == 4) {
if (req.status == 200) {
alert(req.responseText);
document.write("OK");
}
}
};
req.send();
}
</script>
And in chrome extension file getData.htm, how can I get data?
(Edit: what type of data are you sending? Could you pass it through as a JSON encoded string, via GET? JSON.stringify() and JSON.parse() may be of use to you. :)
The following may be useful as a guide for accessing that POST/GET data. :) )
As far as I am aware, this is best done using some form of server side scripting. You could use window.location.search in JS, and split the string and perform the necessary functions, but I think server-side scripting may work best. :)
An example of a JS implementation could be as follows:
var url = window.location.search;
var params = url.substr(url.IndexOf("?") - 1, 30);
This would grab the parameters (starting at ? (inclusive), and continue for 30 chars. You could also use something like var params = url.substr(url.IndexOf("?") - 1, url.length); to get the whole parameters list.
How you use this from then on, is up to you, but you could pass it through a switch() or whatever you need. :)
Obviously, this being a chrome extension would limit your options regarding any server-side processing. :/
Edit: The above would go in getData.htm. :)
Related
I am not even sure that what I ask is possible at all, but maybe somebody would be able to give me some ideas...
Here is the situation. I have a certain third-party Javascript module which is being run in browser. The module exposes an API call which loads some configuration (XML file) from a provided URL. I would like to pass it instead some XML which I generate in my own script. I cannot change the module; so, what I am looking for is some way to specify some URL which will serve my local data. Is there any way to do something like this?
Testing with the "javascript:" pseudo protocol didn't work - making it look like XMLHttpRequest does not accept "pseudo" protocols.
Testing with data URIs did work:
var xmlSource =
`<?xml version="1.0" encoding="UTF-8"?>
<text>
<para>hello world</para>
</text>
`;
var xmlDataURL = "data:text/xml," + xmlSource;
loadConfig( xmlDataURL);
was succesfully sent using a dummy version of loadConfig:
// Dummy loadConfig:
function loadConfig( url)
{ var req = new XMLHttpRequest();
req.open("GET", url);
req.onreadystatechange = function ()
{ if( req.readyState == 4)
console.log(req.responseText);
};
req.send();
}
This question already has answers here:
Pull in JSON data
(3 answers)
Closed 6 years ago.
What I want is simple. Is there any way (including a work around) to make this work?
function loadXMLDoc() {
var request = new XMLHttpRequest();
var gistRawFileUrl = 'https://gist.github.com/kentcdodds/5822336/raw/6ef128c8c8d6fe416782d969efa95d36e0acf374/KentsBlog.md';
request.onreadystatechange = function() {
if (request.readyState === 4 && request.status === 200) {
var gistFileContent = request.responseText;
doSomethingCool(gistFileContent);
}
};
request.open('GET', gistRawFileUrl, true);
request.send();
}
Right now, if I execute this in the console here I'm getting:
XMLHttpRequest cannot load https://gist.github.com/kentcdodds/5822336/raw/6ef128c8c8d6fe416782d969efa95d36e0acf374/KentsBlog.md. Origin http://stackoverflow.com is not allowed by Access-Control-Allow-Origin.
This makes sense, and I know I'm not going to get GitHub to open up their access control, but if there's a work around to this or if I'm doing something wrong that would be great.
I realize that you can get the content of the file, by hitting the JSONP endpoint, but that doesn't give you the newline characters, so what was once this:
Hello World!
You
Rock!
Is now this:
Hello World!YouRock!
Thanks in advance.
Edit The problem with the newlines is something I need to fix on my end, not a Gist thing.
Check out this answer: https://stackoverflow.com/a/10454873/240963
API endpoint will give you content of each file within the Gist, including the formatting. The only downside is that you need to transfer extra data even if you already know the URL for the raw file.
We can simplify the code from the original answer, since you don't want to parse JSON and you probably know the filename:
$.ajax({
url: 'https://api.github.com/gists/'+gistid,
type: 'GET',
dataType: 'jsonp'
}).success( function(gistdata) {
var content = gistdata.data.files[filename].content;
DoSomethingWith(content)
}).error( function(e) {
// ajax error
});
JSFiddle
Using JSONP with raw XHR is a bit more complicated, but you could use something lighter than jQuery.
I have this form to upload an xml file to server, I am using fiddler to monitor each req and resp. So the server sends me a small xml and i would like to receive it in my javascript as XMLHttpRequest makes it happen
Note: I am uploading a file so enctype="multipart/form-data"
var client;
var url_action = "/csm/create.action";
var dataString;
if (window.XMLHttpRequest) {
client = new XMLHttpRequest();
} else {
client = new ActiveXObject("Microsoft.XMLHTTP");
}
if (client.readyState == 4 && client.status == 200) {
alert(client.responseTest);
}
client.open("POST", url_action, true);
client.setRequestHeader("enctype", "multipart/form-data");
client.send();
My question is how can i receive the response from server side to JS variable. In the above code XMLHttpRequest i don't think i can send a multipart request (file upload). So any alternative is welcome. Whichever solution provides me a response is good.
Here is what i am doing, to submit the form. Thanks :)
var url_action="/csm/create.action";
$('#mainForm').attr('action', url_action);
$('#mainForm').submit();
Updated with solution
$(data).find('com\\.abc\\.db\\.ConfigInfo').each(function(){
cfgid=$(this).find('cfgId').text();
cfgname=$(this).find('cfgName').text();
filename=$(this).find('fileName').text();
timestamp=$(this).find('updateDate').text();
alert(cfgid+", "+cfgname+", "+filename+", "+timestamp);
});
You have jQuery available so don't ever create XHR objects manually.
Besides that, you cannot use AJAX for file uploads unless you don't care about compatibility with certain browsers.
Last but not least, you want to use the jQuery form plugin which will automatically fallback to a hidden iframe and a regular form if there is a file input in the form.
Note that you need to wrap your JSON response in <textarea></textarea> for it to work properly though. See http://jquery.malsup.com/form/#file-upload for details. If you want to return XML you don't need to wrap it though - it should work fine without any server-side changes.
I'm trying to do a simple POST from a javascript (google chrome extension) to my google app
I can see that the HTTP POST is indeed sent to the GAE server, but I can't figure how to transfer a simple text string, and use it in the google app.
The goal: send a string from the javascript with xmlhttpRequest, show this string on google-app webpage.
Here's the code of the javascript:
function onRequest(request, sender, sendResponse) {
var url = request;
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://myapp.appspot.com");
xhr.send(url);
// Return nothing to let the connection be cleaned up.
sendResponse({});
};
Here's how I deal with the post in the server side:
def post(self):
url1 = str(self.request.get('url1'))
self.response.headers['Content-Type'] = 'text/html'
self.response.out.write('<p>URL is: %s</p>' % url1)
When I look at the POST response I see
<p>URL is: </p>
where is the var url that was sent?
I got it to work, in a different way. Instead of XMLHttpRequest, I used jquery:
$.post("http://myapp.appspot.com", { url1: request});
and it worked :)
BTW, I also discovered that if you want the chrome extension's html to use jquery, you need to do
<script src="jquery-1.5.1.js"></script>
<script> your code here </script>
(I'm sure it's basic for you guys but fresh for me :)
The content you include with xhr.send() will be in self.request.body, if it's not specified in CGI format. For your simple test, you might also try xhr.send("url1=" + request).
What is the best method to detect xml in JavaScript
e.g. is it possible to detect the mime type of a document - particularly if it is text/xml in JavaScript.
this needs to work in Chrome.
thanks,
Josh
If you are using XMLHttpRequest to get this data, then you can simply check for the Content-Type header using the getResponseHeader method (granted that the server sends the appropriate headers).
var getFile = function(address, responseHandler) {
var req = new XMLHttpRequest();
req.open('get', address, true);
req.onreadystatechange = responseHandler;
req.send(null);
}
var responseHandler = function(resp) {
if ( this.readyState < 4 ) { return; }
console.log(this.getResponseHeader("Content-Type"));
};
getFile("http://zebrakick.com/some/file", responseHandler);
(I seem to be using this code sample a lot...)
You can't determine what the mime-type is with Javascript. I would recommend doing checks on the data returned to see if it is valid XML before you try to parse it. (I'm only assuming what you're trying to do. I can provide a more rigid example if you clarify what your goal is.)
I came across this when looking to determine that a chrome extension script was on an XML page. Maybe this saves someone a few minutes.
In the chrome console and content scripts you can check with:
document.contentType==="application/xml"