В настоящее время я пишу простое расширение Chrome, которое сохраняет текущую веб-страницу в локальном хранилище, когда вы щелкаете значок расширения в заголовке.
Я успешно сохранил URL в локальном хранилище, используя background.js в соответствии с документацией Chrome здесь: 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"
}
}