How to execute a function inside chrome.tabs.executeScript - javascript

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.

Related

Chrome.scripting.executeScript using function on page not defined

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.

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

How to return currentTab.url google chrome extension

chrome.tabs.query({ active: true, currentWindow: true }, ([currentTab]) => { console.log(currentTab.url); });
Code higher works but i want return current tab url.
If i use
return currentTab.url
It returns undefined.

Categories