如何使用Google Chrome扩展程序更改所选文字的CSS [英] How to change CSS of selected text using Google Chrome Extension

查看:577
本文介绍了如何使用Google Chrome扩展程序更改所选文字的CSS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用contextMenus为Chrome浏览器创建了一个扩展,用于更改所选文本的CSS。

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

但我无法访问HTML结构,即parentNode在这个例子中,我可以很容易地选择文本。

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

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

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

如何使用Chrome浏览器扩展实现此功能?

How to implement this using a Chrome Browser Extension?

推荐答案

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

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.

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

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

然后将它添加到 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
    }
]

现在,当在页面中注入脚本时,您可以使用 LAST_SELECTION LAST_ELEMENT 变量来引用最后一个右键单击的元素并编辑其CSS或任何您想要的。

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.

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

var myContextMenuItem = chrome.contextMenus.create({
    "title": "Some title",
    "contexts": ["all"],
    "documentUrlPatterns": ["*://*/*"],
    "onclick": handler
});

最后,在 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
}

这篇关于如何使用Google Chrome扩展程序更改所选文字的CSS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆