Chrome Extension: How to pass a variable from Content Script to background.html
I can't figure out how to pass a variable (or an array of variables) from a content script to a background page. What I'm trying to do is find certain DOM elements with my content script, then send them to my background page so that I can make a cross-domain XMLHttpRequest with them (store them in a database on a different site).
My code is below. I know that the variable named "serialize" is not being passed (and I don't expect it to based on my current code but have it in there so it's easier to see what I want 开发者_如何学Pythonto do.) So how can I pass a variable from a content script to a background page?
My Content Script:
function onText(data) {
alert("Great Success!!");
};
$("#insertprofile").click(function(){
serialize = $(".certaininputs").serialize();
chrome.extension.sendRequest({'action' : 'insertprofile', 'serialize' : serialize}, onText);
});
My Background Page:
<script>
function insertprofile(serialize) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(data) {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
var data = JSON.parse(xhr.responseText);
callback(data);
} else {
callback(null);
}
}
}
var url = ('http://mysite.com/storeindatabase.php?' + serialize);
xhr.open('GET', url, true);
xhr.send();
};
function onRequest(request, sender, serialize) {
if (request.action == 'insertprofile') {
insertprofile(serialize);
}
};
chrome.extension.onRequest.addListener(onRequest);
</script>
Did you missing "...php?serialize=' + serialize)"
on this code:
var url = ('http://mysite.com/storeindatabase.php?' + serialize);
It's should be like this:
var url = ('http://mysite.com/storeindatabase.php?serialize=' + serialize);
Do you mean:
chrome.extension.sendRequest({'action' : 'insertprofile', 'serialize': serialize}, onText);
?
EDIT
function onRequest(request, sender, callback) {
if (request.action == 'insertprofile') {
insertprofile(request.serialize, callback);
}
};
I think your mistake is accessing the serialize instead of request.serialize.
function insertprofile(serialize) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(data) {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
var data = JSON.parse(xhr.responseText);
callback(data);
} else {
callback(null);
}
}
}
var url = ('http://mysite.com/storeindatabase.php?' + serialize);
xhr.open('GET', url, true);
xhr.send();
};
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
if (request.action == 'insertprofile') {
insertprofile(request.serialize);
sendResponse({});
}
});
精彩评论