I've built a chrome extension that keeps track of your visited sites by getting their URLs. The problem is, it only receives the URL of the page when the extension is opened/clicked. How can I make it so it'll "listen" to the sites I visit at all times?
I tried to fix it by making it get the URL on site onl oad, but I think what's happening is that it listens on the EXTENSION onl oad:
window.onload = function () {
chrome.tabs.getSelected(null, function (tab) {
d = document;
f = document.getElementById("history");
var i = d.createElement('li');
i.innerHTML = tab.url;
f.appendChild(i);
d.body.appendChild(f);
localStorage.setItem("pastVisits", f.innerHTML);
});
try { // trycatch because what if there's no history to pull?
document.getElementById("history").innerHTML = localStorage.getItem("pastVisits");
} catch (error) {
// do nothing...
}
}
body {
width: 800px;
height: 600px;
background-color: rgb(155, 155, 155);
color: white;
font-family: 'Courier New', Courier, monospace;
}
<!DOCTYPE html>
<html>
<head>
<title>User Locations</title>
<script src="popup.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<body>
<p id="history">
</p>
</body>
</html>
Added the snippet even though it doesn't work in the snippet for some reason (It does work in the extension though). Here's an image of it:
CodePudding user response:
You will add "history" permission.
// manifest.json
{
"name": "My extension",
...
"permissions": [
"history"
],
...
}
And then, use
// background.js
chrome.history.onVisited.addListener(
result => console.log(result)
)
"Fired when a URL is visited, providing the HistoryItem data for that URL. This event fires before the page has loaded."