chrome plugin前后台通信&共享数据

本文探讨了浏览器插件与后台页面之间的通信机制,包括如何通过内容脚本发送请求并接收响应,以及如何利用本地存储实现数据共享。同时,文章还介绍了Chrome存储与本地存储的区别,并提供了Android不同WebView间共享数据的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

先看一个问题:在访问插件页面的时候,content script是否运行?

答:不运行。


Sending a request from a content script looks like this:

contentscript.js
================
chrome.extension.sendMessage({greeting: "hello"}, function(response) {
  console.log(response.farewell);
});

On the receiving end, you need to set up an chrome.extension.onMessage event listener to handle the message. This looks the same from a content script or extension page.

chrome.extension.onMessage.addListener(
  function(request, sender, sendResponse) {
    console.log(sender.tab ?
                "from a content script:" + sender.tab.url :
                "from the extension");
    if (request.greeting == "hello")
      sendResponse({farewell: "goodbye"});
  });


问:前后台能否通过localstorage共享数据

答:可以。


chrome 的storage比localstorage强在哪?

  • User data can be automatically synced with Chrome sync (using storage.sync).
  • Your extension's content scripts can directly access user data without the need for a background page.
  • A user's extension settings can be persisted even when using split incognito behavior.
  • User data can be stored as objects (the localStorage API stores data in strings).

可以在前后台共享数据

chrome.storage.local.set( {"key":"val"}, function() {
    chrome.storage.local.get( {"key":null}, function(o) {
        alert(o.key);
    });
});

Android不同的webview共享数据localStorage

  • 要有相同的存储数据库
webSettings.setDatabasePath("/data/data/"+this.getPackageName()+"/databases/");
  • 要打开设置
settings.setDomStorageEnabled(true);


参考:

http://developer.chrome.com/extensions/messaging.html

developer.chrome.com/extensions/storage.html


 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值