3

我正在寻找将数据从网站发送到 chrome 扩展的 LocalStorage。

我已经尝试了以下答案,这正是我正在寻找的答案,但它似乎在 Chrome 29 stable 上根本无法运行。任何人都可以建议为什么这可能是/调整?

4

2 回答 2

4

由于安全规则,无法从网站管理扩展程序的本地存储。

但是有一种方法可以让您将消息从网站发送到扩展程序。

因此,您可以使用此方法将数据发送到扩展程序并在扩展程序的背景页面上获取此数据,然后对它做任何您想做的事情(保存到扩展程序的本地存储)。

DOCs中解释得很好,

1.在你的manifest.json,你会让你的网站允许发送消息。

"externally_connectable": {
  "matches": ["*://*.example.com/*"]
}

2.chrome.runtime.sendMessage将在您的网站上提供。(javascript)

chrome.runtime.sendMessage("your extension id will be here", 
                           {data: { anyDataKey : "example"}});

3. 在您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.
  });
于 2013-08-08T22:43:16.567 回答
0

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.

How to send data from webpage to your extension

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);
});

How to receive above external data from our web page into our extension

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//*"]
}
于 2021-02-25T03:10:09.610 回答