Chrome扩展:如何将变量从内容脚本传递到background.html
我不知道如何将变量(或变量数组)从内容脚本传递到后台页面。我想做的是用我的内容脚本找到某些 DOM 元素,然后将它们发送到我的后台页面,以便我可以使用它们创建跨域 XMLHttpRequest(将它们存储在不同站点的数据库中)。
我的代码如下。我知道名为“serialize”的变量没有被传递(我不希望它基于我当前的代码,但将它放在那里,这样更容易看到我想要做什么。)那么我怎样才能传递一个变量从内容脚本到后台页面?
我的内容脚本:
function onText(data) {
alert("Great Success!!");
};
$("#insertprofile").click(function(){
serialize = $(".certaininputs").serialize();
chrome.extension.sendRequest({'action' : 'insertprofile', 'serialize' : serialize}, onText);
});
我的背景页面:
<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>
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 to 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>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您是否缺少
"...php?serialize=' + serialize)"
这段代码:它应该是这样的:
Did you missing
"...php?serialize=' + serialize)"
on this code:It's should be like this:
您的意思是:
?
编辑
Do you mean:
?
EDIT
我认为你的错误是访问序列化而不是 request.serialize。
I think your mistake is accessing the serialize instead of request.serialize.