我正在开发 Chrome 扩展程序,而且我是该流程的新手。我正在开发的扩展程序将 HTML 侧边栏注入(inject)到页面中,将 java 脚本函数注入(inject)到标题中,然后让用户按侧边栏上的按钮来创建/保存我的扩展程序的数据。
但是,当我想保存信息时,我使用localStorage,但是localStorage总是相对于当前网站进行保存。如何使用 localStorage 来保存我们的扩展?
此外,我想在 chrome 扩展中使用一些全局 javascript 变量。这些属于哪里?我知道我目前无法通过注入(inject)的 Javascript 访问它们。
我研究过消息传递,但遇到了一些问题。我不确定它在将 javascript 注入(inject)到页面标题的范围内如何工作。我已尝试使用此示例,但我的扩展程序似乎没有捕获该消息。
// 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
}
});
关于javascript - 注入(inject)的 HTML 访问 Chrome API 和全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15720383/