How to set input on chrome extension to text from dom? - google-chrome-extension

I am trying to get text from the web page on click into the input on my chrome extension.
Content script
document.addEventListener('click', function (e) {
let target = e.target
let text = target.textContent || target.innerText;
chrome.runtime.sendMessage({ text }, function (response) {
console.log(response.farewell);
});
}, false);
and background script
chrome.runtime.onMessage.addListener(
function (request, sender, sendResponse) {
document.getElementById("userinput").value = "My value";
sendResponse({ farewell: request.text });
}
);
My popup.html just has id of 'userinput' and i am getting unchecked runtime.lastError: The message port closed before a response was received. Error

Related

Chrome Extension perform a function when the page changes in current tab

I am wanting to call a function in my popup.js when the page in the tab changes (and is loaded). In my background.js I have this event which is being called as the console is updated.
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
if (changeInfo.status === "complete") {
console.log("Page changed");
showAlert();
}
});
The showAlert() function is in popup.js but I cannot see how to call it. If I add an element and add an eventListener, I can call the function, but I would like to call it from the chrome.tabs.onUpdated.addListener as above (or a different event as long as it fires when the page changes and is loaded)
Edit. From reading the link provided by #wOxxOm I have tried to use messaging.
I have added this to my background.js which is recognising that the page has changed.
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
if (changeInfo.status === "complete") {
console.log(tabId + " : Page Changed : " + tab.url);
chrome.tabs.sendMessage(tabId, {greeting: "hello"}, function(response) {
console.log(response.farewell);
});
}
});
I have added this to popup.js to listen for the event
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
console.log(sender.tab ?
"from a content script:" + sender.tab.url :
"from the extension");
if (request.greeting === "hello") {
sendResponse({farewell: "goodbye"});
}
}
);
This generates an error in the console.
Error handling response: TypeError: Cannot read properties of undefined (reading 'farewell')

Background script: Error: Could not establish connection. Receiving end does not exist

I am trying to send a message from background script to content script in my chrome extension. But it looks like the message gets send before the content script is loaded?
This is the error I get when I am using my extension normally:
Uncaught (in promise) Error: Could not establish connection. Receiving end does not exist.
This is my background script with the tabs.onUpdated function:
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
if (changeInfo.url) {
console.log(changeInfo.url, tabId)
chrome.tabs.sendMessage(tabId, {
url: changeInfo.url,
type: 'URL_CHANGE'
});
}
});
This is my content script receive function:
chrome.runtime.onMessage.addListener((obj, sender, response) => {
console.log('received', obj)
if (obj.type === 'URL_CHANGE') {
console.log('testestsetst')
getAuth()
getUrlType(obj.url)
} else if (obj.type === 'AUTH') {
getAuth()
} else if (obj.type === 'UN-AUTH') {
removeAuth()
}
});
Whenever I run the extension normally I don't see an output from my content script and I get the error as stated above. However, when I debug the background script and step through the code, I get no error and my content script prints everything correctly. Could this be due to the page needing to load? And if so, how do I solve this?
Solved it by checking for tab complete and sending the url through the tab parameter as follows:
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
if (changeInfo.status === 'complete') {
chrome.tabs.sendMessage(tabId, {
url: tab.url,
type: 'URL_CHANGE'
});
}
});
background.js
chrome.runtime.onInstalled.addListener(function (details) {
if (details.reason == "install") {
chrome.tabs.create({ url: chrome.runtime.getURL(`onboard-page.html`) }, function (tab) {
chrome.tabs.onUpdated.addListener(function listener(tabId, changeInfo) {
if (tabId === tab.id && changeInfo.status == 'complete') {
chrome.tabs.onUpdated.removeListener(listener)
// Now the tab is ready!
chrome.tabs.sendMessage(tab.id, "hello")
}
});
});
} else if (details.reason == "update") {
}
});
content-script.js
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse){
console.log(message)
});

sending a message from content script - google extension

Im trying to send a message on every content load like this:
content.js
chrome.runtime.sendMessage({
data: "just an example"
}, function (response) {
console.dir(response)
});
and then send a message back just to test if it works
popup.js
chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
sendResponse({
data: "example answet to the message"
});
});
but the problem is im getting undefined as a response in content. Why?
The point of sending a message from content on page load is to set a badge with a number like this:
chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
chrome.browserAction.setBadgeBackgroundColor({ color: [255, 0, 0, 255] });
chrome.browserAction.setBadgeText({text: `${blockedUsersFromStorage.split(',').length}`});
});

"chrome.runtime.onMessage" : Send response before create new tab [duplicate]

This question already has answers here:
Chrome Extension Message passing: response not sent
(3 answers)
Closed 7 years ago.
I have problem with sending response in chrome.notifications.onClicked.addListener.
content_scripts
chrome.runtime.sendMessage({action:'openlink', url:'http://stackoverflow.com'}, function(response) {
console.log(response);
});
background
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if(request && request.action === 'openlink') {
chrome.notifications.create('MyUniqueID',{
type: 'basic',
title: 'Open link',
message: request.url,
iconUrl: 'icon.jpg'
});
chrome.notifications.onClicked.addListener(function('MyUniqueID') {
sendResponse({action:'notification-clicked'}); // <--- This
chrome.tabs.create({url:request.url});
});
}
});
So I was wondering what I did wrong ?
The sendResponse must be used immediately after received the message as a way to reply to the sender: ok I received your message and it's OK, so you continue with your code.
When you need to send a message like in your situation you need to call again the function:
chrome.tabs.sendMessage
This means to have the chrome.runtime.onMessage.addListener in the background and content.
For reference see: Chrome Extension Message Passing
Nah, Just add return true after
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if(request && request.action === 'openlink') {
chrome.notifications.create('MyUniqueID',{
type: 'basic',
title: 'Open link',
message: request.url,
iconUrl: 'icon.jpg'
});
chrome.notifications.onClicked.addListener(function('MyUniqueID') {
sendResponse({action:'notification-clicked'}); // <--- This
chrome.tabs.create({url:request.url});
});
return true;
}
});

Send one Chrome Extension desktop notification at a time

I am still learning how to create Chrome extensions, but my issue is with the desktop notifications. I am able to trigger the notifications, but when that happens for example I trigger desktop notification for content script 1. The desktop notification also triggers for content script 2. How do I make it so that they do not trigger at the same time, and only when they are called?
Background page
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
// Create a simple text notification
var notifyWinner = webkitNotifications.createNotification('48.png', 'Notification', request.winnerMessage);
notifyWinner.show();
setTimeout(function(){ notifyWinner.cancel(); },10000);
});
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
// Create a simple text notification
var notifyVideo = webkitNotifications.createNotification('48.png', 'Notification', request.videoMessage);
notifyVideo.show();
setTimeout(function(){ notifyVideo.cancel(); },10000);
});
Content Script 1
chrome.extension.sendRequest({winnerMessage: "You won!!!"}, function(response) {
return response;
});
Content Script 2
chrome.extension.sendRequest({videoMessage: "There is a video" + videoURL}, function(response) {
return response;
});
You can simplify the code to only use one onRequest listener and then it will stop displaying duplicate notifications.
background_page
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
// Create a simple text notification
var notify = webkitNotifications.createNotification('48.png', 'Notification', request.message);
notify.show();
setTimeout(function(){ notify.cancel(); },10000);
});
content_script
chrome.extension.sendRequest({
message: "There is a video" + videoURL}, // Change the message here as needed.
function(response) {
return response;
});

Resources