I am creating a chrome extension that allows a user to click and select multiple texts on a web page. The selected text will be displayed on the extension window as the user is selecting the text. The extension will then allow the user to download the list of text selected as an excel file
Here is my code:
Manifest.json
{
"manifest_version": 2,
"name": "Text Selector",
"version": "1.0",
"description": "This extension allows you to select text from web pages.",
"permissions": [
"activeTab",
"https://*/*"
],
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
}
}
popup.html
<!DOCTYPE html>
<html>
<head>
<style>
#selected-text {
height: 200px;
overflow-y: scroll;
border: 1px solid #ccc;
padding: 10px;
}
</style>
</head>
<body>
<h2>Selected Text:</h2>
<div id="selected-text"></div>
<button id="download-button">Download as Excel</button>
</body>
<script src="popup.js"></script>
</html>
popup.js
// Initialize the state of text selection
var isTextSelectionEnabled = false;
// Listen for the user clicking the "Enable Text Selection" button
document.getElementById('enable-text-selection').addEventListener('click', function(event) {
// Toggle the state of text selection
isTextSelectionEnabled = !isTextSelectionEnabled;
// Change the button text based on the state of text selection
if (isTextSelectionEnabled) {
document.getElementById('enable-text-selection').innerText = 'Disable Text Selection';
} else {
document.getElementById('enable-text-selection').innerText = 'Enable Text Selection';
}
});
// Listen for the user clicking on the page
document.addEventListener('mouseup', function(event) {
// Only add the selected text to the list if text selection is enabled
if (isTextSelectionEnabled) {
// Get the selected text
var selectedText = window.getSelection().toString();
if (selectedText) {
// Add the selected text to the list
var selectedTextList = document.getElementById('selected-text');
var newItem = document.createElement('div');
newItem.innerText = selectedText;
selectedTextList.appendChild(newItem);
}
}
});
// Listen for the user clicking the download button
document.getElementById('download-button').addEventListener('click', function(event) {
// Get the list of selected text
var selectedTextList = document.getElementById('selected-text');
var textArray = [];
for (var i = 0; i < selectedTextList.children.length; i++) {
textArray.push(selectedTextList.children[i].innerText);
}
// Convert the text array to a CSV string
var csvString = textArray.join(',');
// Download the CSV string as an Excel file
var link = document.createElement('a');
link.href = 'data:text/csv;charset=utf-8,' + encodeURIComponent(csvString);
link.download = 'selected-text.csv';
link.click();
});
When clicking on any text in a webpage, the popup.html is closing and there is no selected text displayed on it. When downloading the excel it is empty