Manifest v3 inject script from popup.js - javascript

In manifest v2 this code worked and injected the script when button was clicked:
popup.js v2 (works)
document.addEventListener('DOMContentLoaded', function () {
// Get button by ID
var button = document.getElementById('btnScan');
// Define button on click action
button.onclick = function () {
chrome.tabs.executeScript(null, {
file: 'Scripts/script.js'
});
window.close();
}
});
Now in manifest v3, chrome.tabs.executeScript is replaced with chrome.scripting.executeScript.
scripting permission is added in manifest.json.
popup.js v3 (not working)
document.addEventListener('DOMContentLoaded', function () {
// Get button by ID
var button = document.getElementById('btnScan');
// Define Scan button on click action
button.onclick = function () {
chrome.scripting.executeScript
(
{
target: { tabId: null}, // ???????
files: ['Scripts/script.js']
}
);
window.close();
}
});
The problem is that chrome.tabs.executeScript requires tabId value as one of the parameters.
How can I get tabId value in popup.js or convert the manifest v2 version javascript so that it works the same?

Thanks to #wOxxOm who posted a link as a comment.
The solution was to get the active tab and use its tabId.
document.addEventListener('DOMContentLoaded', function () {
// Get button by ID
var button = document.getElementById('btnScan');
button.onclick = injectScript;
});
async function injectScript() {
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
await chrome.scripting.executeScript({
target: { tabId: tab.id },
files: ['Scripts/script.js']
});
window.close();
}

Related

Add or remove content script on click of a toggle button inside a chrome popup?

I am developing my first chrome extension, I want to have a toggle button on my popup which allows users to enable or disable the extension for that site, though not completely disable the extension but technically control the execution of the content.js for that particular domain.
Something similar to
popup.js
const toggleBtn = document.querySelector(".toggle");
toggleBtn.addEventListener("click", function(){
if(toggleBtn.checked === true){
console.log('inject content.js');
}else{
console.log('remove content.js');
}
});
I can see there is a way to inject it but there is no way to remove it.
chrome.scripting.executeScript({
target: {tabId},
files: ['content.js'],
});
Note, I don't want to reload the page but want to disable the content.js. How can I achieve this functionality inside my chrome extension. I see there are many extensions doing this like Adblocker and Wordtune.
I went through few SO threads like this one but most of them are for Manifest V2 and few packages that are recommended are obsolate now. I also could not find a complete example anywhere.
Todo
I should be able to turn the extension on/off for the current domain from within the Popup.
It should store the state inside a chrome.storage.sync so that next time I installed the extension I should not again turn on/off for the selected websites.
As soon as I toggle the button, the changes should be visible if I have opened the same domain in another tab.
The extension's icon should be changed in real time as well e.g grey icon for disabled status
If I close and open a website, the icon and the toggle button should be restored their on/off status and update the icon accordingly.
My Attempt (Solves #toDo 1,2,3,4,5)
background.js
const icons = {
enabled: {
'16': 'icon-16.png',
'19': 'icon-19.png',
'38': 'icon-38.png',
'48': 'icon-48.png',
'128': 'icon-128.png'
},
disabled: {
'16': 'icon-16-off.png',
'19': 'icon-19-off.png',
'38': 'icon-38-off.png',
'48': 'icon-48-off.png',
'128': 'icon-128-off.png'
}
};
const getExtensionStatus = host => new Promise((resolve, reject) => {
chrome.storage.sync.get(host, result => {
if (result[host] !== undefined) {
resolve(result[host]);
} else {
setExtensionStatus(host, true);
}
});
});
const setExtensionStatus = (host, toggleBtnStatus) => {
const data = { [host]: toggleBtnStatus };
chrome.storage.sync.set(data, () => {});
};
chrome.runtime.onInstalled.addListener((details) => {
if (details.reason === "install") {
chrome.action.setIcon({ path: icons.enabled });
}
});
const init = async tab => {
const url = new URL(tab.url);
if (url.protocol !== "chrome-extension:") {
const host = url.host;
const status = await getExtensionStatus(host);
const icon = status ? icons.enabled : icons.disabled;
chrome.action.setIcon({ path: icon });
}
};
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
if (changeInfo.status === "complete") init(tab);
});
chrome.tabs.onActivated.addListener(info => {
chrome.tabs.get(info.tabId, init);
});
chrome.runtime.onMessage.addListener(async (request, sender, sendResponse) => {
if (request.type === "getExtensionStatus") {
const status = await getExtensionStatus(request.host);
sendResponse({ status });
return true;
} else if (request.type === "setExtensionStatus") {
setExtensionStatus(request.host, request.status);
const icon = request.status ? icons.enabled : icons.disabled;
chrome.action.setIcon({ path: icon });
}
});
popup.js
document.addEventListener("DOMContentLoaded", function () {
const toggleBtn = document.querySelector(".toggle");
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
const host = new URL(tabs[0].url).host;
chrome.runtime.sendMessage({ type: "getExtensionStatus", host }, (response) => {
toggleBtn.checked = response.status;
});
toggleBtn.addEventListener("click", () => {
chrome.runtime.sendMessage({ type: "setExtensionStatus", host, status: toggleBtn.checked });
});
});
});
What left?
The content.js is not available after some time of inactiveness of the tab. How can I inject the script again and avoid running event multiple times?
content.js
document.addEventListener("keydown", listenEnterkey);
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.type === "setExtensionStatus") {
console.log(request.status);
if (request.status) {
// Add event listener here
document.addEventListener("keydown", listenEnterkey);
} else {
// Remove event listener here
document.removeEventListener("keydown", listenEnterkey);
}
}
});
For example, if you add a button with a script, I don't think the added button will disappear even if you remove the script.
Therefore, the ON/OFF function is built into the script, and it is operated by the message.
manifest.json
{
"name": "content_scripts + popup",
"version": "1.0",
"manifest_version": 3,
"content_scripts": [
{
"js": [
"matches.js"
],
"matches": [
"<all_urls>"
]
}
],
"host_permissions": [
"<all_urls>"
],
"action": {
"default_popup": "popup.html"
}
}
matches.js
console.log("matches.js");
let isEnabled = true;
console.log(isEnabled);
chrome.runtime.onMessage.addListener((message) => {
switch (message) {
case "on":
isEnabled = true;
break;
default:
isEnabled = false;
break;
}
console.log(isEnabled);
});
popup.js
const send = (s) => {
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
chrome.tabs.sendMessage(tabs[0].id, s);
});
}
document.getElementById("on").onclick = () => {
send("on");
}
document.getElementById("off").onclick = () => {
send("off");
}
popup.html
<html>
<body>
<button id="on">on</button>
<button id="off">off</button>
<script src="popup.js"></script>
</body>
</html>

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

Why does chrome.storage.sync.set not load user setting instantly?

For my chrome extension's options page I have two radio buttons to switch between showing and not showing the buttons on a page. The function works but it takes me a few reloads of the web page before the changes take effect. Does it take some time to save to chrome.storage before the changes take effect/can be used?
here is the JS for my options page:
const saveBtn = document.getElementById('save-btn');
saveBtn.addEventListener('click', () => {
if(document.getElementById('show_btns').checked){
console.log('true');
chrome.storage.sync.set({ btn_disp: true });
} else {
console.log('false');
chrome.storage.sync.set({ btn_disp: false });
}
});
Background script waits for page to load then injects content scripts and css and sends user data with message.
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
//inject the script into page
//only inject on complete load
//listening for the 'complete' message from tabs
if(changeInfo.status === 'complete' && /^http/.test(tab.url)){
chrome.scripting.executeScript({
target: { tabId: tabId },
files: ['./src/js/foreground.js']
})
.then(() => {
console.log('INJECTED');
})
.catch(err => console.log(err));
chrome.scripting.insertCSS({
target: {tabId: tabId},
files: ['./src/css/page_btn_styles.css']
})
.then(() => {
console.log('page_btn_styles.css injected');
sendToForeground();
})
.catch(err => console.log(err));
}
});
//page loaded -> load buttons
function sendToForeground() {
chrome.tabs.query({ active: true, currentWindow: true }, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, { message: 'page_loaded', data: user_data }, (response) => {
console.log('page_loaded message sent');
});
});
}
My content script listens for a message from the background script that the page has loaded. The background script sends the user data object with the message.
//message from background.js that page has loaded
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if(request.message === 'page_loaded'){
const allElements = document.querySelectorAll('*');
for(let i = 0; i < allElements.length; i++) {
if(allElements[i].className.toString().match(/ingredient/g)){
console.log(request.data);
loadPageBtns(request.data);
break;
}
}
}
sendResponse({});
});
JS for loading page buttons in the content script
function loadPageBtns(user_data) {
if(user_data.btn_disp){
//container for buttons on page
let container = document.createElement('div');
container.id = 'btns-container';
//ingredients button
let ingredientsBtn = document.createElement('button');
ingredientsBtn.id = 'ingredients-btn';
ingredientsBtn.classList.add('page-btns');
ingredientsBtn.classList.add('animated');
ingredientsBtn.classList.add('bounceInLeft');
ingredientsBtn.innerText = 'Get Ingredients';
ingredientsBtn.addEventListener('click', () => {
scrollToIngredients();
});
ingredientsBtn.addEventListener('mouseover', () => {
ingredientsBtn.classList.remove('animated');
});
//load event handler for click on recipe
//recipe button
let recipesBtn = document.createElement('button');
recipesBtn.id = 'recipes-btn';
recipesBtn.classList.add('page-btns');
recipesBtn.classList.add('animated');
recipesBtn.classList.add('bounceInLeft');
recipesBtn.innerText = 'Get Recipe';
recipesBtn.addEventListener('click', () => {
scrollToDirections();
});
recipesBtn.addEventListener('mouseover', () => {
recipesBtn.classList.remove('animated');
});
container.appendChild(ingredientsBtn);
container.appendChild(recipesBtn);
document.body.appendChild(container);
}
}
Chrome storage does not seem to save anything when the data is false, i.e. chrome.storage.sync.set({ btn_disp: false });
does not store anything. If it is true then it does store the item.
This can be a problem depending on your default value. If you have a default of TRUE then you end up never being able to store a FALSE value.
I resolved this by storing text true or false rather then boolean.
I can't see your retrieve and default logic so I'm not sure if this is the root of your problem.

(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'})
}
})

onMessage not being executed on Chrome extension

Referencing this post, I am trying to use executeScript or sendMessage to pass a variable to my content.js file. Using Chrome dev tools, I see that it is reaching my content.js file, and it also runs the test alert I insert, but when it gets to the
chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
it skips it entirely. I'm not sure what is happening here?
popup.js
function search() {
var name = document.getElementById('txtSearch').value;
chrome.tabs.executeScript({ file: "jquery.js" }, function () {
chrome.tabs.executeScript(null, {
code: 'var name = ' + name + ';'
}, function () {
chrome.tabs.executeScript({ file: 'content.js' });
});
});
}
document.getElementById('btnSearch').addEventListener('click', search);
or popup.js using sendMessage
function search() {
var name = document.getElementById('txtSearch').value;
chrome.tabs.executeScript({ file: "jquery.js" }, function () {
chrome.tabs.executeScript({ file: 'content.js' }, function () {
chrome.tabs.sendMessage({ name: name });
});
});
}
document.getElementById('btnSearch').addEventListener('click', search);
content.js
alert('hi');
chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
console.log(message.name);
});
Referencing a different answer I found on SO (cant find it atm), I was missing a function to pass the tab id to the content script.
chrome.tabs.query({ active: true }, function (tabs) {
chrome.tabs.sendMessage(tabs[0].id, {'type': type, 'name': name });
});

Categories