簡體   English   中英

Chrome擴展程序將Background.js中的值保存到存儲中並在popup.html上顯示

[英]Chrome Extension Saving Values from Background.js into Storage and displaying on popup.html

我目前正在編寫一個簡單的Chrome擴展程序,當您單擊標題中的擴展程序圖標時,會將當前網頁保存到本地存儲。

我已根據Chrome文檔在此處使用background.js將網址成功保存到本地存儲中: https//developer.chrome.com/extensions/activeTab

我的問題是,當我第一次點擊Chrome擴展圖標時,我的事件會觸發但是我的popup.js出錯了

Uncaught TypeError: Cannot read property 'getSelected' of undefined

background.js

chrome.browserAction.onClicked.addListener(function(tab) {

  console.log('Turning ' + tab.url + ' red!');
  var tabNew = tab.url
  chrome.storage.sync.set({ ["key" + 1]:  tabNew}, function(){
      //  A data saved callback omg so fancy
  });

  chrome.storage.sync.get(/* String or Array */["key" + 1], function(items){
      //  items = [ { "yourBody": "myBody" } ]
      console.log(items)
  });


  chrome.tabs.executeScript({
    code: 'document.body.style.backgroundColor="red"'
  });

  chrome.browserAction.setPopup({popup: 'popup.html'});


});

popup.js

chrome.tabs.getSelected(null, function(tab) {
    document.getElementById('currentLink').innerHTML = tab.url;
});



document.addEventListener('DOMContentLoaded', function() {
    var link = document.getElementById('download');
    // onClick's logic below:
    link.addEventListener('click', function() {
        chrome.storage.sync.get(null, function(items) { // null implies all items
            // Convert object to a string.
            var result = JSON.stringify(items);

            // Save as file
            chrome.downloads.download({
                url: 'data:application/json;base64,' + btoa(result),
                filename: 'filename_of_exported_file.json'
            });
        });        
    });
});

popup.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head> 

    <link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'> 
    <link href='style.css' rel='stylesheet' type='text/css'> 

    <title>Discoveroo</title> 

    <!-- <script type="text/javascript" src="https://www.google.com/jsapi"></script>  -->
    <base target="_blank">

</head>

<body>
<p id="currentLink">Loading ...</p>
<hr />
<ul id="savedLinks"></ul>
<script type="text/javascript" src="popup.js"></script>

<button id="download">Download All</button>
</body>
</html>

的manifest.json

{
  "name": "APPNAME",
  "version": "0.1",
  "manifest_version": 2,
  "description": "APP DESC",
  "permissions": ["activeTab", "storage", "downloads", "<all_urls>"], 
  "background": {
    "scripts": ["background.js"],
    "persistent": true
  },
  "content_scripts": [{
    "matches": ["http://*/*", "https://*/*"],
    "js": ["popup.js"]
  }],
  "browser_action": {
    "default_title": "Add this page to my list"
  },
  "icons": {
    "128": "icon.png"
  }
}
  1. 不要將popup.js用作內容腳本。 您不需要內容腳本。 請參閱體系結構概述 內容腳本對chrome API的訪問權限有限並且在網頁中運行,而不是在browserAction彈出窗口中,這是一個完全獨立的完整擴展頁面,它有自己的chrome-extension:// URL和自己的devtools控制台等,與網絡無關頁。
  2. browserAction.onClicked不能與彈出式html同時工作,所以你應該選擇一個。 在這種情況下,因為您需要顯示彈出頁面,在manifest.json中聲明它,刪除browserAction.onClicked,將其內部代碼放入您的popup.js
  3. 因此,不需要后台腳本
  4. 可能不需要<all_urls>權限,因為您已經擁有activeTab ,在單擊擴展圖標后,您可以完全訪問活動選項卡。
  5. chrome.tabs.getSelected已棄用,最終將被刪除,因此請使用chrome.tabs.query({active: true, currentWindow: true}, tabs => { ... })
  6. 因為您已經在popup.js中獲得了活動URL,所以無需讀取chrome.storage。
  7. 關於“omg so fancy”,回調並不是一種任意的怪異,而是基本事實的結果:API是異步的,因此回調在稍后的時間點被調用,就像一次性的“onload”事件監聽器。 有很多關於異步JavaScript的教程。
  8. 使用安全的textContent屬性而不是可能不安全的innerHTML來顯示純文本字符串,例如URL。

的manifest.json

  • 刪除"background"
  • 刪除"content_scripts"
  • 添加"default_popup"

     "browser_action": { "default_title": "Add this page to my list", "default_popup": "popup.html" }, 

background.js

刪除它。

popup.js

您可能需要的舊后台腳本中唯一的東西是executeScript和sync.set調用。

chrome.tabs.executeScript({
  code: 'document.body.style.backgroundColor="red"'
});

chrome.tabs.query({active: true, currentWindow: true}, ([tab]) => {
  document.getElementById('currentLink').textContent = tab.url;
  chrome.storage.sync.set({key1: tab.url});
});

您還可以加載Mozilla WebExtension polyfill (在popup.js之前使用popup.html中的 <script>標記)並切換到async / await語法而不是回調:

(async () => {
  const [tab] = await browser.tabs.query({active: true, currentWindow: true});
  document.getElementById('currentLink').textContent = tab.url;
  await chrome.storage.sync.set({key1: tab.url});
})();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM