简体   繁体   中英

I am trying to use chrome.storage.sync and chrome.tabs.create to transfer data that user inputed and use it as the url for chrome.tabs api

I am trying to use chrome.storage.sync and chrome.tabs.create to make it so the user puts certain websites in the options menu, and those websites open when the button is clicked.

I am having trouble because I am not sure how to take the input from chrome.storage.syng.get, and give it to chrome.tabs.create, since chrome.tabs.create is asking for a string for the url. I apologize for how awfully this question is worded but hopefully, you can understand through my code.

background script:

chrome.storage.sync.get('website1', function(website1){
  chrome.tabs.create ({url: 'website1'})
});
chrome.storage.sync.get('website2', function(website2){
  chrome.tabs.create ({url: 'website2'})
});
chrome.storage.sync.get('website3', function(website3){
  chrome.tabs.create ({url: 'website3'})
});

In this code that I have here, it just opens a tab trying to get to a website called "website 3" because it thought that was the url, but it is supposed to represent what the user put in. How do I put in the code so that it will take what the user put in and then insert it as the url.

Sorry for how confusingly this is worded I am just having a hard time describing my problem.

The callback receives an object , its each key corresponds to the key you requested. BTW you can request multiple keys in one call:

chrome.storage.sync.get(['website1', 'website2', 'website3'], data => {
  if (data.website1) chrome.tabs.create({url: data.website1});
  if (data.website2) chrome.tabs.create({url: data.website2});
  if (data.website3) chrome.tabs.create({url: data.website3});
});

You can use a loop:

chrome.storage.sync.get(['website1', 'website2', 'website3'], data => {
  for (const url of Object.values(data)) {
    chrome.tabs.create({url});
  }
});

Similarly you can store several keys in one call:

chrome.storage.sync.set({
  website1: 'url1',
  website2: 'url2',
  website3: 'url3',
});

You can store an array of URLs under one key:

chrome.storage.sync.set({
  websites: ['url1', 'url2', 'url3'],
});

...and read it:

chrome.storage.sync.get('websites', data => {
  for (const url of data.websites || []) {
    chrome.tabs.create({url});
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM