我正在寻找将数据从网站发送到 chrome 扩展的 LocalStorage。
我已经尝试了以下答案,这正是我正在寻找的答案,但它似乎在 Chrome 29 stable 上根本无法运行。任何人都可以建议为什么这可能是/调整?
我正在寻找将数据从网站发送到 chrome 扩展的 LocalStorage。
我已经尝试了以下答案,这正是我正在寻找的答案,但它似乎在 Chrome 29 stable 上根本无法运行。任何人都可以建议为什么这可能是/调整?
由于安全规则,无法从网站管理扩展程序的本地存储。
但是有一种方法可以让您将消息从网站发送到扩展程序。
因此,您可以使用此方法将数据发送到扩展程序并在扩展程序的背景页面上获取此数据,然后对它做任何您想做的事情(保存到扩展程序的本地存储)。
在DOCs中解释得很好,
manifest.json
,你会让你的网站允许发送消息。"externally_connectable": {
"matches": ["*://*.example.com/*"]
}
chrome.runtime.sendMessage
将在您的网站上提供。(javascript)chrome.runtime.sendMessage("your extension id will be here",
{data: { anyDataKey : "example"}});
background.js
创建外部消息的消息侦听器。chrome.runtime.onMessageExternal.addListener(
function(request, sender, sendResponse) {
if (request.data)
alert("Hi, there is message from the website");
var data = request.data;
// now the data is on your extension side, just save it to extension's localstorage.
});
In order to send data from any webpage into your extension you need to send that data into your extension and in your extension background file you have to receive it using runtime.onMessageExternal
Yes, @okan-kocyigit answer provide pretty well info on how we can allow our extension to connect and receive data from any external web page. I would just like to update with latest doc link and latest syntax. Please check this latest chrome extension doc to get a clear idea.
as per the doc You can send any data to your extension by doing like below your webpage's javascript file
// The ID of the extension we want to talk to.
var yourExtensionId = "abcdefghijklmnoabcdefhijklmnoabc";
// Make a simple request to send data to your extension:
chrome.runtime.sendMessage(yourExtensionId, {accessToken: "logged user's accessToken"},
//below callback is optional
function(response) {
if (!response.success)
handleError(url);
});
chrome.runtime.onMessageExternal.addListener(
function(request, sender, sendResponse) {
// console.log(sender) will be from where we sending data
// console.log(request) data object which we send from our webpage
if (request.accessToken) {
// now we have the accessToken from our web page
// so we can use it in our extension by storing into localStorage of extension
chrome.storage.sync.set({accessToken: request.chromeAccessToken}, function() {
// console.log('accessToken value is set to ' + user.accessToken);
});
}
follow this chrome doc link runtime.onMessageExternal for more details
And please don't forget to add externally_connectable in your manifest.json file to get this running.
"externally_connectable": {
"matches": ["*://*.yourapp.com/*", "*://yourapp.com//*"]
}