当用户点击扩展图标时,我想通过 chrome 扩展保存事件选项卡的 url 链接。 url 应该保存在本地存储中,并且应该一直保存到事件窗口未关闭为止。我正在尝试将 url 保存在数组 tablink
这是manifest.json
{
"manifest_version": 2,
"name": "saveLink",
"version": "1.0",
"browser_action": {
"default_icon": "xyz.png",
"default_popup": "popup.html",
"default_title": "saveLink"
},
"permissions": [
"activeTab",
"storage",
"tabs"
]
}
这是我的 popup.js
,其中包含 popup.html
var tablink = [];
function getTabUrl(){
chrome.tabs.getSelected(null,function(tab) {
var len = tablink.length;
if(len == 0){
tablink[0] = tab.url;
}
else {
tablink[len] = tab.url;
}
console.log(tablink);
}
}
document.addEventListener("DOMContentLoaded", function() {
getTabUrl();
link.addEventListener('click', function() {
chrome.tabs.update({url: 'https://www.google.com/'});
});
});
目前,控制台没有打印任何东西。此外,该扩展有一个重定向到指定链接 (google.com) 的按钮,在我编写用于保存选项卡链接的代码之前它工作正常,但现在不工作了。请说明是否需要添加更多内容。
最佳答案
打开弹出窗口时将当前选项卡 URL 保存到列表
弹出窗口
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
var tabUrl = tabs[0].url;
chrome.storage.local.get('urlList', function(item){
var newUrlList = item.urlList;
newUrlList.push(tabUrl);
console.log(newUrlList);
chrome.storage.local.set({urlList: newUrlList});
});
});
Explanation: Basically,
tabs.query
gets a list of tabs, and it takes search terms includingactive:true
andcurrentWindow:true
. With those parameters it only ever returns one tab but the result is still treated as a list, so we usetabs[0]
. Then you get the current tab list that you saved in storage and set the variablenewUrlList
to the tab list. To add a new item to the list, a better way thantablink[0] = newvalue
is 'pushing' the variable to the list, withnewUrlList.push(tabUrl)
. Then we replace the stored list with the newUrlList.
编辑:
如果 urlList
已设置为 chrome.storage 中的列表,则上面的代码有效,下面的代码确保 urlList
在不存在的情况下被初始化
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
var tabUrl = tabs[0].url;
chrome.storage.local.get({'urlList':[]}, function(item){
var newUrlList = item.urlList;
if (newUrlList.indexOf(tabUrl) === -1) {
newUrlList.push(tabUrl);
}
console.log(newUrlList);
chrome.storage.local.set({urlList: newUrlList});
});
});
Explanation:
chrome.storage.local.get({'urlList':[]})
gets the value of urlList if it exists, but if it doesn't exist yet it initialises it to[]
. Also, I think you're going to add this code to a function so it only runs when you click a button in popup.html, but I added an if statement to check if the URL wasn't there so that only new URLs are added.
此外,在使用 chrome.storage 时,至少清除存储以检查它是否正常工作对我很有帮助:chrome.storage.local.clear();
关于javascript - 如何使用 JS 通过 chrome 扩展在本地保存用户访问的 url?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50000346/