I am trying to pass a parameter to the function called by chrome.scripting.executeScripts but it seems that the function can't get parameters passed from the extension!
My extension contains several inputs, when one input is focused on, the extension should pass a certain parameter from the input dataset to the function executed by chrome scripting to set the value of an input in the page, author
let bookInputs = [...document.getElementsByClassName('book-input')];
bookInputs.forEach(bookInput=> {
bookInput.addEventListener('focus', () => getBook(bookInput.dataset.author))
})
async function getBook(author) {
let [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
chrome.scripting.executeScript({
target: { tabId: tab.id },
function: () => enterBookAuthor(author)
})
}
function enterBookAuthor(author) {
const book= document.getElementById('book-author'); //an input in the page
book.value = author;
}
But this code doesn't manage to achieve the mission, so
Why can't functions executed by chrome scripting receive parameters from the extension and what can i do to fix it??
You should use the args property, because scripting does not carry over any of the current execution context of the function.
Here's an example:
let bookInputs = [...document.getElementsByClassName('book-input')];
bookInputs.forEach(bookInput=> {
bookInput.addEventListener('focus', () => getBook(bookInput.dataset.author))
})
async function getBook(author) {
let [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
chrome.scripting.executeScript({
target: { tabId: tab.id },
func: enterBookAuthor,
args: [author], // this is the args property.
})
}
function enterBookAuthor(author) {
const book= document.getElementById('book-author'); //an input in the page
book.value = author;
}
Here are the links to the docs: https://developer.chrome.com/docs/extensions/reference/scripting/#runtime-functions