如何使用Google Chrome扩展更改所选文本的CSS

How to change CSS of selected text using Google Chrome Extension

本文关键字:文本 CSS 何使用 Google Chrome 扩展      更新时间:2023-09-26

我正在为Chrome浏览器做一个扩展,它使用contextMenu来更改所选文本的CSS。

但我无法访问HTML结构,即所选文本的parentNode,因为在本例中我可以很容易地访问。

var selection = window.getSelection();

如果在浏览器中默认使用,这将返回所选文本的parentNode,我可以稍后使用它来更改CSS。

如何使用Chrome浏览器扩展实现这一点?

由于Chrome不允许您使用上下文菜单与单击的元素交互,您必须创建一个内容脚本,该脚本存储页面上最后一个右键单击的元素,因此当用户右键单击任何元素时,您都可以使用它。

首先,您必须创建一个save_last_element.js内容脚本,如下所示:

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);

然后将其添加到manifest.json:中

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

现在,在页面中注入脚本时,您将能够使用LAST_SELECTIONLAST_ELEMENT变量来引用最后一个右键单击的元素,并编辑其CSS或任何您想要的内容。

在你的background.js中,你应该这样做:

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
    });
});

请注意,上下文菜单是在chrome.runtime.onInstalled侦听器中注册的,因为上下文菜单注册是持久的,只需要在安装扩展时进行。

最后,在您的script.js文件中:

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
}