I started to learn chrome extensions, I wanna make an extension with a list of phrases to send in twitch chat.
I have no intention of using the twitch api.
The first message is sent as it should, but the next ones nothing happens.
There’s a log that shows that messages arrive on the page, I don’t know what I’m doing wrong.
This is what I have:
manifest.json
{
"manifest_version": 2,
"name": "Default Messages",
"version": "0.1",
"offline_enabled": true,
"background": {
"persistent": false,
"scripts": ["background.js"]
},
"content_scripts": [{
"matches": ["*://*.twitch.tv/*"],
"js": ["content.js"]
}],
"page_action": {
"default_title": "Default messages",
"default_popup": "popup.html"
}
}
background.js
chrome.runtime.onMessage.addListener((msg, sender) => {
if (msg.from === "twitch" && msg.subject === "chat") {
chrome.pageAction.show(sender.tab.id);
}
});
content.js
chrome.runtime.sendMessage({
from: "twitch",
subject: "chat",
});
chrome.runtime.onMessage.addListener((msg, sender, response) => {
if (msg.from === "defaultMessages" && msg.subject === "newMessage") {
console.log(msg);
let input = document.querySelectorAll("textarea")[0];
let buttons = document.querySelectorAll("button");
input.textContent = msg.content;
input.dispatchEvent(new Event("input", { bubbles: true }));
buttons.forEach((button) => {
if (button?.dataset?.aTarget == "chat-send-button") {
button.dispatchEvent(new Event("click", { bubbles: true }));
}
});
response({
from: "twitch",
subject: "messageSent",
id: msg.id,
});
}
});
popup.js
window.addEventListener("DOMContentLoaded", () => {
let tab_id = undefined;
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
tab_id = tabs[0].id;
});
document.querySelectorAll("button").forEach((button) => {
button.addEventListener("click", function (e) {
if (!e.target.disabled) {
let content = e.target.textContent;
let id = e.target.id;
chrome.tabs.sendMessage(
tab_id,
{
from: "defaultMessages",
subject: "newMessage",
content,
id,
},
(resp) => {
document.getElementById(resp.id).disabled = true;
}
);
}
});
});
});
popup.html
<!DOCTYPE html>
<html lang="en">
<head>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<script type="text/javascript" src="./popup.js"></script>
</head>
<body>
<div class="container">
<div class="card mt-1" style="width: 15rem;">
<div class="card-body">
<div class="btn-group-vertical">
<button type="button" class="btn btn-outline-primary" id="hello">Hello</button>
<button type="button" class="btn btn-outline-primary" id="hi">Hi</button>
<button type="button" class="btn btn-outline-primary" id="how">How are you doing?</button>
</div>
</div>
</div>
</div>
</body>
</html>