我正在开发一个Chrome扩展,我是这个过程的新手。扩展我正在工作注入一个HTML侧边栏到页面,注入java-script函数的头,然后让用户按下侧边栏上的按钮来创建/保存我的扩展的数据。
然而,当我想保存信息时,我使用localStorage,然而,localStorage总是保存相对于当前网站。我如何使用localStorage来保存我们的扩展?
此外,我想在chrome扩展中使用一些全局javascript变量。这些属于哪里?我知道我目前不能从注入的Javascript访问它们。
我研究了消息传递,我在这方面遇到了一些麻烦。我不确定它是如何在注入javascript到页面头的范围内工作的。我试着用这个例子工作,但我的扩展似乎没有捕捉到消息。
// This function is called in the injected header javascript.
function sendToExtension() {
setTimeout(function() {
console.log('page javascript sending message');
window.postMessage({ type: 'page_js_type',
text: "Hello from the page's javascript!"},
'*' /* targetOrigin: any */);
}, 10);
}
// This is installed in a background script.
window.addEventListener('message', function(event) {
console.log('content_script.js got message:', event);
});
你必须使用Chrome的sendMessage函数和onMessage监听器。见下文:
function sendToExtension() {
console.log('Sending message');
chrome.runtime.sendMessage({ext: "myExtension"}, function(response) {
console.log(response.ack);
});
}
// Listener - Put this in the background script to listen to all the events.
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.ext) {
console.log('Message received from ' + request.ext);
sendResponse({ack:'received'}); // This send a response message to the requestor
}
});