The Chrome extension cannot set the value of the acquired HTML element to Chrome.storage.

Asked 2 years ago, Updated 2 years ago, 314 views

I am creating a Chrome extension, but I would like to retrieve HTML elements and save them to Chrome.storage.

For pages with only h1 tags, if you run JavaScript below,

>Value is set to <h1>Hello, world</h1>
>Value currently {key:[Prototype]]:Object}

The output is such that it is not reflected.

Please let me know.

 const h1 = document.querySelector('h1')

chrome.storage.local.set({
  "key"—h1,
}, function(){
  console.log('Value is set to',h1)
})

chrome.storage.local.get(['key'], function(result){
  console.log('Value currently is', result)
})
<body>
  <h1>Hello, world</h1>
</body>

manifest.json

{
  "manifest_version"—3,
  "name": "Get Elements",
  "description": "Get elements and save them to storage",
  "version": "1.0",
  "action": {
    "default_popup": "popup.html"
  },
    "content_scripts":[
        {
        "matches": ["<all_urls>",
        "js": [
            "content-script.js"
        ],
        "run_at": " document_end",
        "all_frames"—true
        }
    ],
  "commands": {
    "_execute_action": {
      "suggested_key": {
        "default": "Ctrl+Shift+H",
        "mac": "MacCtrl+Shift+H"
      },
      "description": "Run extension."
    }
  },
  "permissions": [
    "activeTab",
    "contextMenus",
    "clipboardWrite",
    "scripting",
    "tabs",
    "storage"
  ],
  "options_page": "options.html"
}

javascript google-chrome chrome-extension

2022-10-05 01:00

1 Answers

When saving to storage, the object cannot be saved as it is, so serialization occurs (because the data can only be saved as a byte column).

https://developer.chrome.com/docs/extensions/reference/storage/#:~:text=Primitive%20values%20such%20as%20number%20will%20serialize%20as%20expected.%20Values%20with%20a%20typeof%20%22object%22%20and%20%22function%20will%20type%20to%20serialize%20%20%20%20%20%Arcease%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20d%20Regex%20 (serialize%20using%20their%20String%20representation).

In addition to the primitive values, the array, Date and Regex seem to be the expected serialization, but consider that other objects, including DOM, cannot basically be retained.

I don't know what behavior you're expecting, but if you want to keep it as HTML, would it be possible to extract HTML as text in Element.outerHTML?


2022-10-05 01:00

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.