![](/img/trans.png)
[英]How to get the selected text inside google docs document into a chrome extension?
[英]How to change CSS of selected text using Google Chrome Extension
我正在为使用contextMenus更改所选文本的CSS的Chrome浏览器进行扩展。
但是我无法访问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_SELECTION
和LAST_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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.