Chrome.scripting.executeScript using function on page not defined - javascript

The following is my code
document.getElementById('randomname').onclick = () => {
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
chrome.scripting.executeScript({
target: {tabId: tabs[0].id},
function: randomName
});
});
}
function randomName() {
// Your script goes here
var name = extern.generateRandomName()
alert(name);
}
My issue is that when this code is run, because it is not defined in my js file, it says it is not defined. BUT, this function extern.generateRandomName() is defined on the website this code is running on.

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

Manifest v3 inject script from popup.js

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

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://*", ...]

How to execute a function inside chrome.tabs.executeScript

I have this code:
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.query({ active: true, currentWindow: true }, tabs => {
chrome.tabs.executeScript(
tabs[0].id,
{
code: // HERE I want much more space to write
'var to_filter = document.querySelector("iframe").contentDocument.querySelector("body").querySelectorAll("tbody")[1].innerHTML; alert(to_filter);'
},
downloadFiles
);
});
});
function downloadFiles(resultsArray){
}
I have to execute a lot of code inside the code tag, and after that, I have to send a list of links to the downloadFiles function. The problem is that I cannot write all the code in the code field, I would like to use a function instead. How can I call a function to execute instead of writing only in that line?
------ Update
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.query({ active: true, currentWindow: true }, tabs => {
chrome.tabs.executeScript(
tabs[0].id,
{
code:'(${ inContent })()' // ERROR
//'var to_filter = document.querySelector("iframe").contentDocument.querySelector("body").querySelectorAll("tbody")[1].innerHTML; alert(to_filter);'
},
downloadFiles
);
function inContent() {
alert("test")
}
});
});
I get: VM138:1 Uncaught SyntaxError: Unexpected token '{' in the commented line above.

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