Jake Durell
Jake Durell

Reputation: 179

How to access chrome storage from multiple HTML files in a chrome extension

I already have an options page on my chrome extension, and I am trying to create several other pages in my extension directory which need to make use of the chrome storage data gathered by popup.html.

I have tried adding the new HTML page to the options page attribute in the manifest.json file, but that prevents the extension from loading. When accessing the chrome storage with a "DOMContentLoaded" event on the new non-options HTML page, as follows:

document.addEventListener("DOMContentLoaded", function () {
    getData();
}, false);

function getData() {
    chrome.storage.local.get(['data'], function (result) {
        console.log(result.data);
        setFormData(result.data[0])
    });
}


function setFormData(data){
    console.log(data)
}

I get this error:

Uncaught TypeError: Cannot read property 'local' of undefined

I assume means that newHTML.html is not making use of the manifest file, but I am note sure how I tell the manifest file about newHTML.

Here is the manifest file:

{
    "name": "ExtensionName!",
    "version": "1.0",
    "description": "A Chrome Extension!",
    "permissions": ["activeTab", "declarativeContent", "storage","<all_urls>"],
    "background": {
      "scripts": ["background.js"],
      "persistent": false
    },
    "options_page": "formMenu.html",
    "page_action": {
      "default_popup": "popup.html",
      "default_icon": {
        "16": "images/get_started16.png"
      }
    },
    "icons": {
      "16": "images/get_started16.png"
    },
    "manifest_version": 2,
    "content_security_policy": "script-src 'self' https://code.jquery.com https://cdnjs.cloudflare.com https://stackpath.bootstrapcdn.com https://use.fontawesome.com; object-src 'self'",
    "externally_connectable": {
      "ids": ["*"]
    }
  }

Upvotes: 1

Views: 665

Answers (1)

Jean-Alphonse
Jean-Alphonse

Reputation: 816

Your code has acces to chrome.storage when it is running in the context of your extension.
If you open file://.../newHTML.html, it's just a normal javascript context.

Use chrome.runtime.getURL("newHTML.html") to get an extension url which looks like this: chrome-extension://[id]/newHTML.html.

Also there is no need to wait for DOMContentLoaded to acces localStorage.

Upvotes: 1

Related Questions