[英]How do I automatically save URLs in a Google Chrome extension when a user visits a specific site?
我是 web 編程的新手,但不是一般的編程新手。 我正在嘗試構建一個 Google Chrome 擴展程序,每當用戶訪問 StackOverflow.com 上的任何頁面時,它都會自動保存 URL。 然后我想在擴展彈出窗口中顯示 URL 列表。
到目前為止,我已經決定我需要一個 Page Action 擴展,因為我只希望它在 StackOverflow 頁面上處於活動狀態。 我了解訪問選項卡及其 URL 的不同方式,但我不知道將代碼放在哪里。
例如,我不確定是否需要內容腳本和/或背景腳本。 我也很困惑 Listeners 以及我是否需要在內容腳本和事件頁面或彈出腳本之間發送消息。 這是我到目前為止所擁有的:
manifest.json
"manifest_version": 2,
"name": "Stack Overflow visit history",
"version": "1.0",
"description": "This Chrome extension stores your Stack Overflow URL visits.",
"icons": {
"128": "icon128.png",
"48": "icon48.png",
"16": "icon16.png"
},
"page_action": {
"default_icon": "icon16.png",
"default_popup": "popup.html",
"default_title": "StackOverflowVisits"
},
"background": {
"scripts": ["eventPage.js"],
"persistent": false
},
"content_scripts": [
{
"matches": ["https://stackoverflow.com/*"],
"js": ["content.js", "jquery-3.5.1.min.js"]
}
],
"permissions": [
"webNavigation",
"tabs",
"https://stackoverflow.com/*"
]
}
popup.html
<html>
<head>
<title>Stack Overflow Visit History</title>
<style>
body {min-width: 250px;}
</style>
<script src="jquery-3.5.1.min.js"></script>
<script src="popup.js"></script>
</head>
<body>
<h2>StackOverflowVisits</h2>
<div id="newUrlList"></div>
</body>
</html>
popup.js
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});
});
});
內容.js
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
chrome.extension.getBackgroundPage().console.log(tab.url);
chrome.storage.sync.set({tabId : tab.url})
});
內容腳本無法訪問所有擴展 API,它們無權訪問chrome.tabs.onUpdated
(更多詳細信息)。
在這種情況下,您不需要內容腳本,您可以在后台腳本中添加該偵聽器,如果未設置為persistent: false
,此腳本將在瀏覽器打開的整個過程中運行。
關於上下文之間的通信:在這種情況下,如果您只有一個后台腳本和一個彈出窗口,您可以使用chrome.extension.getBackgroundPage()
從彈出窗口訪問后台腳本,或者您可以簡單地將數據保存在存儲中的后台腳本並在彈出窗口打開時從商店加載它。 如果您正在尋找實時更新,您可以使用通信端口或請求/響應方案(更多詳細信息)。
我不知道您是否已經這樣做了,因為您還沒有共享后台腳本 ( eventPage.js
) 的內容,但是為了在特定頁面上顯示頁面操作,您必須注冊它,您可以在此處了解更多詳細信息
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.