I’m new to chrome extensions. I am trying to develop a Chrome extension that can automatically fill forms and scrape data from specific websites.
Basically, in the website, I have an object with id “nome:nome:inputId”. When I go to chrome console and run:
var a = document.getElementById("nome:nome:inputId").value
It returns to me the value I want. But I’m not able to do that in the chrome extension. It prints nothing. Why could this be happening?
The full code is below:
// manifest.json
{
"manifest_version": 3,
"name": "Simple Element Value Printer",
"version": "1.0",
"description": "Print the value of a specific element on the page",
"permissions": [
"activeTab",
"scripting"
],
"action": {
"default_popup": "popup.html",
}
}
// popup.html
<!DOCTYPE html>
<html>
<head>
<title>Simple Element Value Printer</title>
<style>
body {
width: 300px;
padding: 10px;
font-family: Arial, sans-serif;
}
#value {
margin-top: 10px;
padding: 10px;
border: 1px solid #ccc;
border-radius: 5px;
background-color: #f9f9f9;
}
</style>
</head>
<body>
<h3>Element Value</h3>
<div id="value">Click the button to get the value</div>
<button id="print-value">Get Element Value</button>
</body>
</html>
// popup.js
console.log("popup");
document.getElementById('fillPdfButton').addEventListener('click', () => {
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
chrome.scripting.executeScript({
target: { tabId: tabs[0].id },
files: ['content.js']
});
});
});
// content.js
const element = document.getElementById("nome:nome:inputId");
if (element) {
console.log("Valor do elemento:", element.value);
} else {
console.log("Elemento não encontrado.");
}
//background.js
chrome.action.onClicked.addListener((tab) => {
chrome.scripting.executeScript({
target: { tabId: tab.id },
files: ['content.js']
});
});