Chrome extension: how to call alarm from popup.js - google-chrome

I'm doing chrome extension. On click button in popup.html a call scote to call alarm ffrom background.js.
popup.js:
document.addEventListener('DOMContentLoaded', function() {
var checkPageButton = document.getElementById('checkPage');
checkPageButton.addEventListener('click', function() {
//call alarm
chrome.runtime.sendMessage({greeting: "alert"}, function(response) {
//NONE response, why?
console.log(response.farewell);
alert("response:" + response.farewell);
});
document.getElementById('checkPage').innerHTML = "SET";
}, false);
}, false);
background.js:
//alarm
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.greeting == "alert"){
alert("alert alarm");
sendResponse({farewell: "goodbye"});
}
}
);
manifest.json
{
"name": "AlarmText",
"version": "0.0.1",
"manifest_version": 2,
"permissions": ["alarms", "http://my-url.com"],
"icons": { "128": "icons/icon128.png",
"64": "icons/icon64.png",
"32": "icons/icon32.png" },
"browser_action": {
"default_title": "Alarm test",
"default_popup": "popup.html"
},
"background": {
"scripts": ["background.js"],
"persistent": true
}
}
popup.html
<!doctype html>
<html>
<head>
<title>popup</title>
<script src="popup.js"></script>
</head>
<body>
<div id="out">???</div>
<button id="checkPage">Refresh</button>
</body>
</html>
What is wrong? In call alarm: chrome.runtime.sendMessage({greeting: "alert"}, function(response) is not response

Related

what does this error message on my chrome extension, from popup.html mean and how to fix it?

So as you already read in the title my problem hast todo with popup.html
I have no idea what the problem is please help me!
this is the error code
Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist.
Stacktrace
popup.html:0 (Anonyme Funktion)
popup.html is:
<!DOCTYPE html>
<html>
<head>
<style>
#popup-container {
width: 600px;
height: 800px;
}
</style>
<title>DissBott</title>
</head>
<body>
<h1>ChatGPT Extension</h1>
<p>input</p>
<textarea id="input"></textarea>
<br>
<button id="submitButton">Submit</button>
<button id="clearButton">Clear</button>
<br>
<p>Response:</p>
<p id="response"></p>
<script src="popup.js"></script>
</body>
</html>
popup.js is:
// Popup Script
//background.js
const submitButton = document.getElementById("submitButton");
const clearButton = document.getElementById("clearButton");
const promptTextarea = document.getElementById("prompt");
const responseParagraph = document.getElementById("response");
submitButton.addEventListener("click", function() {
// onClick's logic below:
// Get the prompt from the textarea
const prompt = input;
// Send the message to the background script
chrome.runtime.sendMessage({
message: "clicked_browser_action",
prompt: prompt
}, function(response) {
// Display the response
responseParagraph.innerText = response;
});
});
clearButton.addEventListener("click", function() {
// Clear the textarea
promptTextarea.value = "";
// Clear the response
responseParagraph.innerText = "";
});
my manifest.json
{
"manifest_version": 3,
"name": "DissBot",
"description": "This is an extension that uses the ChatGPT model.",
"version": "1.0",
"host_permissions": [
"https://api.openai.com/"
],
"action": {
"default_popup": "popup.html"
},
"background": {
"script": ["bg.js"]
}
}
I tried to make a chrome extension it didnt work.
Here is a sample of chrome.runtime.sendMessage.
manifest.json
{
"name": "hoge",
"version": "1.0",
"manifest_version": 3,
"background": {
"service_worker": "background.js"
},
"action": {
"default_popup": "popup.html"
}
}
popup.html
<html>
<body>
<button id="send">Send</button>
<script src="popup.js"></script>
</body>
</html>
popup.js
document.getElementById("send").onclick = () => {
chrome.runtime.sendMessage("send", (respose) => {
console.log(respose);
});
}
background.js
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
console.log(message);
sendResponse("response");
return true;
});

Chrome extension error "runtime.lastError: The message port closed before a response was received. "

I am buidng a chrome app to click a element after pageloaded :
manifest.json:
{
"manifest_version": 2,
"name": "click chapter-btn",
"version": "1.0",
"browser_action":{ },
"background": {
"scripts": ["background.js"]
},
"permissions": [
"tabs",
"storage",
"https://www.youtube.com/*"
],
"content_scripts": [
{
"matches": ["https://www.youtube.com/*"],
"all_frames": true,
"js": ["contentScript.js"]
}
]
}
contentscript.js:
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if(document.readyState !== 'complete') {
window.addEventListener('load',afterWindowLoaded);
} else {
afterWindowLoaded();
}
function afterWindowLoaded(){
setTimeout(()=>{
var btn = document.querySelector('.ytp-chapter-title-prefix')
btn?.click()
},3000)
}
return true
});
background.js:
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab){
if(changeInfo && changeInfo.status == "complete"){
if(!tab.url.includes('https://www.youtube.com/watch')){
return
}
chrome.tabs.sendMessage(tabId, {data: tab}, function(response) {});
}
});
I searched some solutions in internet, 'add "return true" to chrome.runtime.onmessage listener',but still show this error, Dont know what to do.

Cannot Send Message from Popup to Content

I want to send message from Popup.js into Content script by this code:
popup.js
chrome.tabs.query({ active: true, currentWindow: true }, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, { xpath: xpath });
});
And Receive it in Content Script by this code:
content.js
chrome.runtime.onMessage.addListener(gotMessage());
function gotMessage(request, sender, sendResponse) {
alert("Hello");
}
My Manifest is:
manifest.json
{
"manifest_version": 2,
"name": "Auto Clicker",
"description": "Set Time, Set Element to Click, Start!",
"version": "0.1",
"permissions": ["tabs", "<all_urls>"],
"browser_action": {
"default_icon": {
"16": "images/icon-16x16.png",
"24": "images/icon-24x24.png",
"32": "images/icon-32x32.png"
},
"content_scripts": [
{
"matches": [
"<all_urls>"
],
"js": ["content.js"]
}
],
"default_title": "Auto Clicker",
"default_popup": "popup.html"
},
"icons": {
"16": "images/icon-16x16.png",
"24": "images/icon-24x24.png",
"32": "images/icon-32x32.png",
"128": "images/icon-128x128.png"
}
}
Why it is not Working? the messages is'nt send to the Content script.
My issue is solved in this way:
// Inject Trigger to the current active Web Page
function injectTheScript() {
let xpath = document.getElementById("xpath-input").value || "";
chrome.tabs.query({ active: true, currentWindow: true }, function(tabs) {
chrome.tabs.executeScript({
code: `
(function () {
let btn = new XPathEvaluator()
.createExpression("${xpath}")
.evaluate(document, XPathResult.FIRST_ORDERED_NODE_TYPE).singleNodeValue;
btn.click();
})();
`
});
});
}

calling executeScript in onUpdated handler (chrome extension)

I have this code:
chrome.tabs.onUpdated.addListener(function(id, changes, tab)
{
if (changes.status != "complete") return false;
chrome.tabs.executeScript(id, {code: "alert('Page loaded.');"});
});
It's executes in debugger, but does not works. Why?
Try this exactly as defined here.
manifest.json
{
"manifest_version": 2,
"name": "Execute script app",
"version": "1.0",
"background": {
"persistent":true,
"page":"background.html"
},
"content_scripts": [{
"matches": ["http://*/*"],
"js": ["app.js"]
}
],
"permissions": [
"tabs",
"http://*/*"
]
}
background.html
<script src="background.js"></script>
background.js
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab){
if(changeInfo && changeInfo.status == "complete"){
chrome.tabs.executeScript(tabId, {code: "alert('Page loaded.');"});
}
});
app.js
//well this is just empty since ur not doing anything here

Using Google Chrome ttsengine for speech input

I am developing a chrome extension and using tts and ttsengine for speech i/o. But my extension have my chrome to crash without a useful error code (Chrome quits unexpectedly with Process: Google Chrome [888])
When I call the javascript method chrome.experimental.speechInput.start(function(){}) chrome crashes.
I tried another extension provided by google which is Speech Recognizer and it works well, also the speech input in google.com works well. Experimental flag has been set.
Is there any additional permission to give or any other procedure to make speech-to-text work?
My manifest.json:
{
"name": "my_extension",
"version": "0.1",
"manifest_version": 2,
"description": "my description",
"icons": {
"16": "icon16.png",
"128": "icon128.png"
},
"app": {
"launch": {
"local_path": "/twitter/index.html"
}
},
"offline_enabled": true,
"permissions": [
"experimental",
"unlimitedStorage",
"https://api.twitter.com/*",
"ttsEngine",
"tts"
],
"tts_engine": {
"voices": [{
"lang": "de",
"event_types": ["end"]
}]
}
}
My .js file:
function startSpeechInput() {
chrome.experimental.speechInput.onError.addListener(recognitionFailed);
chrome.experimental.speechInput.onResult.addListener(recognitionSucceeded);
chrome.experimental.speechInput.onSoundEnd.addListener(recognitionEnded);
chrome.experimental.speechInput.isRecording(function (recording) {
if (!recording) {
chrome.experimental.speechInput.start({ 'language': 'en-US' }, function(){
//TODO
}
console.log("Voice recognition started!");
});
}
else {
console.log('Pressed Record while it is already recording. Do nothing...');
}
});
}
It worked for me with your content after some changes.
Screenshot
Manifest.json:
{
"name": "my_extension",
"version": "0.1",
"manifest_version": 2,
"description": "my description",
"icons": {
"16": "icon.jpg",
"128": "icon.jpg"
},
"app": {
"launch": {
"local_path": "index.html"
}
},
"background":{
"scripts": ["background.js"]
},
"offline_enabled": true,
"permissions": [
"experimental",
"unlimitedStorage",
"https://api.twitter.com/*",
"ttsEngine",
"tts"
],
"tts_engine": {
"voices": [{
"lang": "de",
"event_types": ["end"]
}]
}
}
index.html
<html>
<head>
<script src="index.js">
</script>
</head>
<body>
</body>
</html>
index.js
function recognitionFailed(error) {
alert("Speech input failed: " + error.code);
}
function recognitionSucceeded(result) {
alert("Recognized '" + result.hypotheses[0].utterance + "' with confidence " + result.hypotheses[0].confidence);
}
function startSpeechInput() {
chrome.experimental.speechInput.onError.addListener(recognitionFailed);
chrome.experimental.speechInput.onResult.addListener(recognitionSucceeded);
chrome.experimental.speechInput.onSoundEnd.addListener(function (){
console.log("started");
});
chrome.experimental.speechInput.isRecording(function (recording) {
if (!recording) {
chrome.experimental.speechInput.start({ 'language': 'en-US' }, function(){
console.log("Voice recognition started!");
});
}
else {
console.log('Pressed Record while it is already recording. Do nothing...');
}
});
}
startSpeechInput();
background.js
function dummy() {
}