I’m trying to a chrome extension to track tweets that I type out and store them into a variable that can be displayed in the html code. However, each time I do a tweet there is just an undefined value.
Here is the code:
script.js
document.addEventListener('DOMContentLoaded', function() {
const tweetButtonSelector = 'div[data-testid="tweetButtonInline"]';
const tweetTextareaSelector = 'div[aria-label="Tweet text"]';
function trackTweet() {
setTimeout(() => {
const tweetTextarea = document.querySelector(tweetTextareaSelector);
if (tweetTextarea) {
const tweetInput = tweetTextarea.innerText;
console.log('User is tweeting:', tweetInput);
chrome.storage.local.set({
tweetInput: tweetInput
}, function() {
console.log('Tweet content saved:', tweetInput);
});
}
}, 500);
}
const observer = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
if (mutation.type === 'childList' && mutation.addedNodes.length > 0) {
mutation.addedNodes.forEach((node) => {
if (node.querySelector && node.querySelector(tweetButtonSelector)) {
const tweetButton = node.querySelector(tweetButtonSelector);
tweetButton.addEventListener('click', trackTweet);
}
});
}
});
});
observer.observe(document.body, {
childList: true,
subtree: true,
});
const tweetButton = document.querySelector(tweetButtonSelector);
if (tweetButton) {
tweetButton.addEventListener('click', trackTweet);
}
});
popup.js
document.addEventListener('DOMContentLoaded', function () {
chrome.storage.local.get(['tweetInput'], function (result) {
console.log('Retrieved tweet content:', result.tweetInput);
const tweetContent = document.getElementById('tweetContent');
tweetContent.textContent = result.tweetInput || 'No tweet tracked yet.';
});
});
hello.html
<!DOCTYPE html>
<html>
<head>
<title>Tweet Tracker</title>
<script src="script.js"></script>
<script src="popup.js"></script>
</head>
<body>
<p>Tweet Tracker</p>
<input type="text" id="InputText" placeholder="Input Text">
<button id="SubmitButton">Submit</button>
<p id="output">a</p>
<p id="tweetContent">No tweet tracked yet.</p>
</body>
</html>
manifest.json
{
"manifest_version": 3,
"name": "Tweet Tracker",
"description": ".",
"version": "1.0",
"permissions": [
"activeTab",
"background",
"scripting",
"storage"
],
"content_scripts": [
{
"matches": ["https://x.com/*"],
"js": ["script.js"]
}
],
"host_permissions": [
"https://x.com/*"
],
"action": {
"default_popup": "hello.html",
"default_icon": "hello_extensions.png"
}
}
I tried testing the code by putting in
chrome.storage.local.get('tweetInput', function(result) {
console.log(result.tweetInput);
});
and
chrome.storage.local.get(null, console.log)
in the console, but that also returned undefined
.