How to change CSS of selected text using Google Chrome extension

I am making a Chrome browser extension that uses contextMenus to change the CSS of the selected text.

But I can’t access the HTML structure, that is, the parentNode of the selected text, as I can do very easily in this example.

var selection = window.getSelection(); 

If used by default in the browser, this returns the parentNode of the selected text, which I can use to change CSS later.

How to implement this using the Chrome browser extension?

+5
source share
1 answer

Since Chrome does not allow you to interact with the element that you clicked using the context menu, you need to create a script content that stores the last element that was right-clicked on the page, so when the user right-clicks on any element, you can use it.

First you need to create a save_last_element.js content script, for example:

 var LAST_SELECTION, LAST_ELEMENT; document.body.addEventListener('contextmenu', function(e) { LAST_SELECTION = window.getSelection(); LAST_ELEMENT = e.target; // this will update your last element every time you right click on some element in the page }, false); 

Then you add it to your manifest.json :

 "permissions": ["*://*/*"], // don't forget to set the permissions for all the pages "content_scripts": [ { "matches": ["*://*/*"], "js": ["/path/to/save_last_element.js"], "run_at": "document_idle", "all_frames": true } ] 

Now when you enter the script on the page, you can use the LAST_SELECTION and LAST_ELEMENT variables to refer to the last element with a right click and edit its CSS or whatever.

In your background.js you should do something like this:

 function handler(info, tab) { // here you can inject a script inside the page to do what you want chrome.tabs.executeScript(tab.id, {file: '/path/to/script.js', all_frames: true}); } var myContextMenuItem = chrome.contextMenus.create({ "title": "Some title", "contexts": ["all"], "documentUrlPatterns": ["*://*/*"], "onclick": handler }); 

And finally, inside your script.js file:

 if (LAST_SELECTION) { // do whatever you want with the information contained in the selection object } if (LAST_ELEMENT) { // do whatever you want with the element that has been right-clicked } 
+5
source

Source: https://habr.com/ru/post/1203433/


All Articles