Make Chrome extension works in background - javascript

I made a Chrome extension to do some routine tasks that I have to do as checking some values and clicking some buttons.
It works really well when it's on focused tab but it stops working when it is in background or not focused.
My background.js:
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
if(changeInfo.status == 'complete') {
chrome.tabs.query({
active: true,
currentWindow: true
}, function(tabs) {
//checking something
chrome.tabs.query({currentWindow: true, active: true},
function(tabs) {
chrome.tabs.sendMessage(tab.id, {type: 1});
});
});
}
});
My content.js:
chrome.runtime.onMessage.addListener(function(request, sender, response) {
if(request.type == 1) {
//actions
}
});
I don't really know what I can do to let this works in background too.
Thanks for the help

Related

How to use executeScript like a content script in chrome extension

I am using execute script, but it only works when a user clicks on the icon. How can I make it so that it runs when the user moves to a new page like a content script?
I tried calling the function within the page but that also does not work.
const page = () => {
alert("popup");
}
function test(){
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
chrome.scripting.executeScript({
target: { tabId: tabs[0].id },
func: page
});
});
}
test()//does not work

currentWindow: true not calling the correct tab using Chrome Extention

Solved
I had the wrong source unpacked files added...
With the script below i get the error:
Uncaught (in promise) Error: Cannot access contents of url "https://www.reddit.com/". Extension manifest must request permission to access this host.
Script:
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
chrome.scripting.executeScript({
target: { tabId: tabs[0].id },
args: [VerCodeComplete],
func: (VerCodeComplete) => {
document.getElementById("subject").value = VerCodeComplete;
document.getElementById("text").value = VerCodeComplete;
},
});
});
I have used chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => { in other locations within the .js without issues.
The way I understand this, the script is not trying to run in the correct window and tab.
If I only have one Chrome window open this works as expected, with more than one window, the error above appears.
Is there something obvious I missed?
Permissions from manifest:
"permissions": ["tabs" , "scripting" , "activeTab"],
These functions work as expected
//Change the language in KS from EN to NO
$("#Change_btn").click(function () {
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
url = tabs[0].url.replace("en-US", "nb-NO");
chrome.tabs.update({ url });
});
});
//Change the language in KS from NO to EN
$("#Change_btn_en").click(function () {
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
url = tabs[0].url.replace("nb-NO", "en-US");
chrome.tabs.update({ url });
});
});
The following does not work as expected
//Generate Email code Code_email_btn_en
function Code_email_en() {
const generateRandomNumber = (min, max) => {
return Math.floor(Math.random() * (max - min) + min);
};
var VerCodeEN = generateRandomNumber(111111, 999999);
var VerCodeText = "Verification code: ";
var VerCodeComplete = VerCodeText + VerCodeEN;
//Auto-paste to Email
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
chrome.scripting.executeScript({
target: { tabId: tabs[0].id },
args: [VerCodeComplete],
func: (VerCodeComplete) => {
document.getElementById("subject").value = VerCodeComplete;
document.getElementById("text").value = VerCodeComplete;
},
});
});
}
These are all in the same .js file, and functions are called from main .html document.
Language change script changes the URL as expected in the currently active window and tab.
The code generator works as long as there is only one Chrome window. With multiple chrome windows it does not call the actually active tab and window.
Cannot access contents of url "https://www.reddit.com/". Extension manifest must request permission to access this host.
So you need to add the url where you execute the script in your permission array in the manifest
permission: ["https://*", ...]

(Easy Fix) How to insert div via content.js Google Chrome Extension?

I'm want to create an overlay via content script (content.js) for my google chrome extension. How should I do this?
Here is the code that executes the content script:
chrome.webNavigation.onCommitted.addListener(function() {
chrome.windows.getCurrent(function (currentWindow) {
chrome.tabs.query({ active: true, windowId: currentWindow.id }, function (activeTabs) {
activeTabs.map(function (tab) {
chrome.tabs.executeScript(tab.id, { file: 'contentScript.js', allFrames: false });
});
});
});
}, {url: [{urlMatches : 'https://mail.google.com/'}]});
Here is my contentScript.js
window.addEventListener('DOMContentLoaded', setUpOverlay, false);
function setUpOverlay(){
//Set up overlay div in here
}
The best way to achieve what you want is to use the chrome message api and pass a message to the content script to execute the code
here is how it works:
//popup.js
chrome.tabs.query({active:true,currentWindow:true},(tabs)=>{
chrome.tabs.sendMessage(tabs[0].id,'execoverlay',(resp)=>{
console.log(resp.msg)
})
})
//contentScript.js
chrome.runtime.onMessage.addListener((request,sender,sendMessage)=>{
if(request==='execoverlay'){
// your code goes here
sendMessage({msg:'recieved'})
}
})

Sending messages from devtools panel to new tab in Chrome extensions

I should send data from my devtools panel to tab. When I send a message using chrome.tabs.sendMessage, why is it not received?
panel.js
$(".options").on("submit", "form", function(e) {
e.preventDefault();
newTabPort = chrome.runtime.connect({ name: "new tab" });
newTabPort.postMessage($(this).serializeArray());
});
background.js
chrome.runtime.onConnect.addListener(function(port) {
port.onMessage.addListener(function(message) {
console.log(message);
});
if (port.name == "new tab") {
chrome.tabs.create({'url': chrome.extension.getURL('page/request_sending_page.html')}, function(tab) {});
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
var activeTab = tabs[0];
chrome.tabs.sendMessage(activeTab.id, {message: "olololololololo"});
});
}
});
my_extension_page.js
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
$("body").append("Hello world <br>");
$("body").append(request.message);
});
Thank you!
All Chrome API with function callbacks are asynchronous, so in your code chrome.tabs.create is executed after the entire function code has completed, thus chrome.tabs.query on the next line doesn't see the newly created tab.
Move the code that should work with the result of the asynchronous call into the callback
Wait for the new tab to be completely loaded before sending the message
There's no need for chrome.extension.getURL when you open the tab from background script.
chrome.tabs.create({url: '/page/request_sending_page.html'}, function(tab) {
var newTabId = tab.id;
chrome.tabs.onUpdated.addListener(function onComplete(tabId, info, tab) {
if (tabId == newTabId && info.status == "complete") {
chrome.tabs.onUpdated.removeListener(onComplete);
chrome.tabs.sendMessage(tabId, {message: "olololololololo"});
}
});
});
P.S. manifest.json: "permissions": ["tabs"]

Display current URL in a chrome extension

After doing some research, the code that I have come up with is this:
var outUrl;
// first get the windowid
chrome.windows.getCurrent(function(window) {
// then get the current active tab in that window
chrome.tabs.query({
active: true,
windowId: window.id
}, function (tabs) {
var tab = tabs[0];
document.write(tab.url)
});
});
This is in a javascript file which is called from my popup html file. It does not, however display the URL of the current website, instead it displays nothing.
I have found multiple posts about this on this and other websites but I haven't been able to implement any of the supposed solutions.
Any help would be greatly appreciated.
Maybe this is what your looking for....
chrome.tabs.query({'active': true, 'windowId': chrome.windows.WINDOW_ID_CURRENT},
function(tabs){
alert(tabs[0].url);
}
);
And the tabs permission needs to be set in the manifest...
manifest.json
"permissions": [
"tabs"
]
I had the same issue. I wrote this extension to display the current URL user is browsing now in the popup.
manifest.js
"permissions": [
"tabs"
]
popup.js
function getCurrentTabUrl(callback) {
var queryInfo = {
active: true,
currentWindow: true
};
chrome.tabs.query(queryInfo, function(tabs) {
var tab = tabs[0];
var url = tab.url;
callback(url);
});
}
function renderURL(statusText) {
document.getElementById('status').textContent = statusText;
}
document.addEventListener('DOMContentLoaded', function() {
getCurrentTabUrl(function(url) {
renderURL(url);
});
});
Solution:
Get the URL of currently selected tab for Chrome Extension
This code is to get parts of URL, because in tabs[0].url we cannot get parts of URL like host, hostname, origin, port, etc...
chrome.tabs.query({ currentWindow: true, active: true }, function (tabs) {
let link = document.createElement('a');
link.href = tabs[0].url;
})
Further using basic js to get its part:
link.host = "password remember.web.app"
You can use other like link.hostname, link.hash, link.host, link.href, link.origin, .link.pathname, link.protocol, link.search
Hope it solves your problem!

Categories