如何在options.js中设置变量chrome.storage.sync并在background.js中调用它

时间:2016-08-16 05:35:24

标签: javascript google-chrome-extension

此扩展程序允许用户使用多功能框中的关键字选择他们希望快速搜索的网站。

这是我的options.html。此文件应该允许用户选择网站首选项并将其保存到chrome.storage.sync。我设置了默认搜索google:

<!DOCTYPE html>
<html>
<head><title>Search Options</title></head>
<body>

Search:
<select id="url">
    <option value="https://google.com/search?q=">Site1</option>
    <option value="url#2.com?search=">
    Site2
    </option>
</select>

<div id="status"></div>
<button id="save">Save</button>

<script src="options.js"></script>
</body>
</html>

我的选项.js。该文件应包含保存和恢复选项的功能:

// Saves options to chrome.storage
function save_options() {
  var url = document.getElementById('url').value;
  chrome.storage.sync.set({prefSite: url}, function() {
    // Update status to let user know options were saved.
    var status = document.getElementById('status');
    status.textContent = 'Options saved.';
    setTimeout(function() {
          status.textContent = '';
    }, 750);
  });
}

// Restores select box and checkbox state using the preferences
// stored in chrome.storage.
function restore_options() {
  // Use default site: Google
  chrome.storage.sync.get({prefSite: 'https://google.com/search?q='}, function(items) {
    document.getElementById('url').value = items.prefSite;
  });
}
document.addEventListener('DOMContentLoaded', restore_options);
document.getElementById('save').addEventListener('click',
    save_options);

和我的background.js。在此文件中,我允许用户使用关键字从多功能框中搜索其选定的网页:

function resetDefaultSuggestion() {
  chrome.omnibox.setDefaultSuggestion({
    description: 'Search for: %s'
  });
}

resetDefaultSuggestion();

chrome.omnibox.onInputCancelled.addListener(function() {
  resetDefaultSuggestion();
});


chrome.omnibox.onInputEntered.addListener(function(text) {
  var prefSite = chrome.storage.sync.get("prefSite", function (obj) {
    console.log(obj);
  });
  var SearchURL = prefSite + text;
  chrome.tabs.create({url: SearchURL });
});

当我尝试搜索时,我会看到this page。任何想法为什么这不起作用?

0 个答案:

没有答案