【发布时间】:2017-09-05 13:27:50
【问题描述】:
每次打开新链接或单击“离开”链接时,如何使弹出窗口中添加的内容不会消失,我对此非常困惑。我已经阅读了有关内容脚本、后台脚本等的内容,但我真的不知道如何将其实现到我自己的源代码中。下面是我的 popup.html、popup.js 和我的 manifest.js 文件。
{
"manifest_version": 2,
"name": "URL_save",
"description": "This extension saves an URL and renames the title to the user's wishes and hyperlink the title.",
"version": "0.1",
"browser_action": {
"default_icon": "/img/icon.png",
"default_popup": "popup.html",
"default_title": "See your saved websites!"
},
"permissions": [
"tabs"
]
}
弹出 html:
<html>
<head>
<title>Your articles</title>
<link href="/css/style.css" rel="stylesheet"/>
<script src="/js/underscore-min.js"></script>
<script src="/js/popup.js"></script>
</head>
<body>
<div id="div">No content yet! Click the button to add the link of the current website!</div>
<div><ul id="list"></ul></div>
<br/>
<button id="button">Add link!</button>
</body>
</html>
popup.js:
// global variables
var url;
// event listener for the button inside popup window
document.addEventListener('DOMContentLoaded', function() {
var button = document.getElementById('button');
button.addEventListener('click', function() {
addLink();
});
});
// fetch the URL of the current tab, add inside the window
function addLink() {
// store info in the the queryInfo object as per:
// https://developer.chrome.com/extensions/tabs#method-query
var queryInfo = {
currentWindow: true,
active: true
};
chrome.tabs.query(queryInfo, function(tabs) {
// tabs is an array so fetch the first (and only) object-elemnt in tab
// put URL propery of tab in another variable as per:
// https://developer.chrome.com/extensions/tabs#type-Tab
url = tabs[0].url;
// format html
var html = '<li><a href=' + url + " target='_blank'>" + url + '</a><br/></li>';
// change the text message
document.getElementById("div").innerHTML = "<h2>Saved pages</h2>";
// get to unordered list and create space for new list item
var list = document.getElementById("list");
var newcontent = document.createElement('LI');
newcontent.innerHTML = html;
// while loop to remember previous content and append the new ones
while (newcontent.firstChild) {
list.appendChild(newcontent.firstChild);
}
});
}
在这张图片中,您可以看到当我第一次添加链接但随后(仅)关闭弹出窗口并再次打开它时会发生什么:
【问题讨论】:
-
目前这个问题有点过于宽泛,无法提供完整的代码答案。有一些选择(例如,如果您只想存储此会话的 URL,跨 Chrome 关闭/重新启动,或跨使用此配置文件的所有计算机)来限制答案集,以便将其降低到特定的关于如何存储和恢复数据的答案。
标签: javascript html google-chrome google-chrome-extension firefox-addon-webextensions