Skip to content Skip to sidebar Skip to footer

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 selecte

Solution 1:

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:

varLAST_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:

functionhandler(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
}

Post a Comment for "How To Change Css Of Selected Text Using Google Chrome Extension"