Skip to content

Instantly share code, notes, and snippets.

@tezansahu
Last active May 5, 2023 03:41
Show Gist options
  • Save tezansahu/807007097e8f83a92e7f64d2bd74567c to your computer and use it in GitHub Desktop.
Save tezansahu/807007097e8f83a92e7f64d2bd74567c to your computer and use it in GitHub Desktop.
// Inject _getSelectedTextFromTab into current page and
// populate the textarea for user input in the popup with the selected text
function getSelectedText() {
// Get information about the currently active tab
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
let tab = tabs[0];
// Inject JavaScript into the active tab to get the text selected by the user
chrome.scripting.executeScript(
{
target: { tabId: tab.id }, // Specify a target to inject JavaScript
function: _getSelectedTextFromTab, // Function to be injected into the target
},
([res]) => {
// If selection is not empty, populate the input textarea
if (res["result"] !== "") {
document.getElementById("input_text").value = res["result"];
}
}
);
});
};
// Get the selected text from the current page
function _getSelectedTextFromTab() {
var selection = window.getSelection().toString();
return selection;
}
// Trigger the injection of script to get user selected text and
// populate the input textarea whenever the DOM content is loaded
// (without waiting for images and stylesheets to finish loading)
document.addEventListener("DOMContentLoaded", getSelectedText);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment