且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从Chrome扩展程序访问(当前打开的域/选项卡的)IndexedDB

更新时间:2023-12-05 19:17:10

要访问当前选项卡的indexeddb,请在manifest.json中的"permissions"标签中添加"activeTab",然后创建一个内容脚本,该内容脚本将有助于访问indexeddb在网页上下文中运行时,然后将创建的内容脚本添加到manifest.json文件中的"content_scripts"标签中. 对于manifest.json中的Eg,添加以下内容:

To access indexeddb of current tab add "activeTab" to "permissions" tag in manifest.json, Then create a content script, content script will be helpful in accessing the indexeddb as it runs in context of webpages, then add the content script created to the "content_scripts" tag in manifest.json file. For Eg in manifest.json add the following:

"permissions": ["activeTab"],
  "content_scripts": [
  {
  "matches": ["add the domains of the webpages where content script needs to run"],
  "js": ["contentScript.js"]
  }
]

有关比赛的更多信息,请点击此处: https://developer.chrome.com/extensions/match_patterns .

For more info on matches check out here:https://developer.chrome.com/extensions/match_patterns .

在内部内容脚本中添加打开存储,然后在对象存储上执行事务并在对象存储上执行查询. 对于内容脚本中的Eg,添加以下内容:

Inside content script add open the store and then perform transaction on the object store and perform queries on the object store. For Eg in content script add following:

if (!("indexedDB" in window)) {
  alert("This browser doesn't support IndexedDB");
 } else {
  let indexdb = window.indexedDB.open("firebaseLocalStorageDb", 1);
  indexdb.onsuccess = function() {
  let db = indexdb.result;
  let transaction = db.transaction("firebaseLocalStorage", "readwrite");
  let storage = transaction.objectStore("firebaseLocalStorage");
  console.log(storage.getAll());
 };
}

上面的代码的解释: 它访问窗口对象,并打开版本为"1"的商店"firebaseLocalStorageDb",然后在成功访问该对象后,它会寻找结果并在位于商店内部的对象商店"firebaseLocalStorage"上执行事务.最后,查询对象存储存储"的实例以获取所有键值对. 有关更多信息,请检查: https://javascript.info/indexeddb

Explanation of the above code: It accesses the window object and opens the store "firebaseLocalStorageDb" with version "1", then after successfully accessing the object it looks for the result and performs transaction on the objectstore "firebaseLocalStorage" residing inside the store. Finally query the instance of objectstore "storage" to get all the key-value pairs. For more info check: https://javascript.info/indexeddb