在过去的两天里,我一直在努力让它发挥作用,作为最后的手段,我在这里问。我查看了 StackOverflow 上所有与消息传递相关的帖子、一些博客,当然还有 Google 的消息传递页面。
我构建的 APP 将在包含某些内容的页面中查找链接并替换它的开头。例如,将在 url 中查找“google.com”并将开头替换为“ask.com”。
我遇到的问题是我想将此变量存储在似乎发生的本地存储变量中。但是,当刷新页面时,不会使用传递的新 url。我已经去掉了一些杂乱无章的东西,制作了一个简化版本,以便于调试。请帮忙!很快就没有头发了!
localStorage["talktest1"]
包含应该更改为从 popup.js 传递的新 URL。然后,当下次加载替换脚本时,它应该使用新talktest1
变量,但是它继续使用旧的“www.google.co.uk”变量。
Manifest.js
:
{
"name": "Talk Talk",
"version": "1.0",
"description": "Tests stuff.",
"browser_action": {
"default_icon": "img/icon16.png",
"default_popup": "popup.html"
},
"options_page": "options.html",
"permissions": [
"tabs", "*://*/*"
],
"background": {
"scripts": ["js/jquery-1.7.2.min.js","js/bg.js"]
},
"icons": { "16": "img/icon16.png",
"48": "img/icon48.png",
"128": "img/icon128.png" },
"content_scripts": [
{
"matches": ["*://*/*"],
"js": ["js/jquery-1.7.2.min.js","js/bg.js"],
"run_at": "document_end"
}
]
}
popup.js
:
$(document).ready(function() {
chrome.extension.getBackgroundPage().alert_this();
$('.link_change').click(function() { // when a link is clicked - url is grabbed from a 'href'
chrome.extension.sendRequest({localstorage: "http://www.something.com"}, function(response) {
var email = response.value;
chrome.extension.getBackgroundPage().alert_this();
});
return false;
});
});
bg.js
:
if(!talktest1){
var talktest1;
}
if(!localStorage["talktest1"]){
localStorage["talktest1"] = "http://www.google.co.uk";
}
talktest1 = localStorage["talktest1"];
chrome.extension.onRequest.addListener(
function(request, sender, sendResponse) {
localStorage["talktest1"] = request.localstorage;
talktest1 = request.localstorage;
sendResponse({value: localStorage.talktest1});
}
);
function alert_this(){
alert("localstore|" + localStorage["talktest1"]);
alert("talktest1|" + talktest1);
}
$("a[href*='google.com']").each(function(){
this.href = this.href.replace('http://www.ask.com',talktest1);
});