Chrome拡張機能には解決できないバグがあります。 拡張機能のインストール時にユーザーがデータを送信すると、chrome.storage.sync.set()が格納されます。ユーザーがGmailの[作成]ボタンをクリックすると、コンテンツスクリプトがメッセージを送信し、入力されたデータが応答として送信されます。初めてGmailを読み込むと、データは「未定義」に戻ります。私がそれを修正できる唯一の方法は、 'alert();'を追加することです。私のコードに入れてください。それは本当に不便で、私はそれを修正する他の方法を見つけることができません。Chrome拡張機能にバグがあります
background.js
var name, title, company, email, photo, phone;
chrome.runtime.onConnect.addListener(function(port) {
console.assert(port.name == "knockknock");
port.onMessage.addListener(function(msg) {
chrome.storage.sync.get("name",function(data){
name = data.name;
});
chrome.storage.sync.get("title",function(data){
title = data.title;
});
chrome.storage.sync.get("company",function(data){
company = data.company;
});
chrome.storage.sync.get("email",function(data){
email = data.email;
});
chrome.storage.sync.get("photo",function(data){
photo = data.photo;
});
chrome.storage.sync.get("phone",function(data){
phone = data.phone;
});
alert();
if (msg.reason == "getInfo"){
port.postMessage({name: name, title: title, company: company, email: email, photo: photo, phone: phone});
}
});
});
setup.js(データは最初に入力されている場所です)
$('.ee-required').slideUp(400,function(){
$('.ee-form-saved').slideDown();
var name = document.getElementsByClassName('ee-form-name')[0].value;
var title = document.getElementsByClassName('ee-form-title')[0].value;
var company = document.getElementsByClassName('ee-form-company')[0].value;
var email = document.getElementsByClassName('ee-form-email')[0].value;
var photo = document.getElementsByClassName('ee-form-photo')[0].value;
var phone = document.getElementsByClassName('ee-form-phone')[0].value;
chrome.storage.sync.set({'name': name});
chrome.storage.sync.set({'title': title});
chrome.storage.sync.set({'company': company});
chrome.storage.sync.set({'email': email});
chrome.storage.sync.set({'photo': photo});
chrome.storage.sync.set({'phone': phone},function(){
setTimeout(function(){window.close()},1000);
});
});
content.js(これはchrome.runtimeでbackground.jsからデータを取得します)
var name, title, company, email, photo, phone;
function getSignature(){
var port = chrome.runtime.connect({name: "knockknock"});
port.postMessage({reason: "getInfo"});
port.onMessage.addListener(function(msg) {
name = msg.name;
title = msg.title;
company = msg.company;
email = msg.email;
photo = msg.photo;
phone = msg.phone;
console.log(name + " " + title + " " + company + " " + email + " " + photo + " " + phone);
});
}
getSignature();
読み、学ぶ:https://stackoverflow.com/questions/18699075/callback-returns-undefined-with-chrome-storage-sync-get/https://stackoverflow.com/questions/11688171/コール後のクロムタブ - クエリ結果が利用できない/ https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous- –
を呼び出すことができます。コンテンツスクリプト自体で 'chrome.storage。*。get'を呼び出すことができます。 – Xan