Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change CSS of selected text using Google Chrome Extension

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

But I am not able to access the HTML structure i.e. parentNode of the selected text as I can do very easily in this example.

var selection = window.getSelection();

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

How to implement this using a Chrome Browser Extension?

like image 218
Sahil Avatar asked Sep 25 '14 20:09

Sahil


1 Answers

Since that Chrome doesn't let you interact with the element you have clicked on using the context menu, you have to create a content script that stores the last element that has been right-clicked on the page, so when the user right-clicks any element, you'll be able to use it.

First you have to create a save_last_element.js content script, like this:

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'll add it in your manifest.json:

"permissions": ["*://*/*"],
"content_scripts": [
    {
        "matches": ["*://*/*"],
        "js": ["/path/to/save_last_element.js"],
        "run_at": "document_idle",
        "all_frames": true
    }
]

Now, when injecting a script in the page, you'll be able to use the LAST_SELECTION and LAST_ELEMENT variables to refer to the last right-clicked element and edit its CSSs or whatever you want.

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', allFrames: true});
}

chrome.runtime.onInstalled.addListener(function() {
    chrome.contextMenus.create({
        "title": "Some title",
        "contexts": ["all"],
        "documentUrlPatterns": ["*://*/*"],
        "onclick": handler
    });
});

Note that the context menu is being registered inside a chrome.runtime.onInstalled listener, since context menus registrations are persistent and only need to be done when installing the extension.

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
}
like image 198
Marco Bonelli Avatar answered Nov 01 '22 11:11

Marco Bonelli