Sah*_*hil 5 javascript css google-chrome selection google-chrome-extension
我正在为使用contextMenus更改所选文本的CSS的Chrome浏览器进行扩展.
但是我无法访问HTML结构,即所选文本的parentNode,因为在这个例子中我可以很容易地做到.
var selection = window.getSelection();
Run Code Online (Sandbox Code Playgroud)
如果在浏览器中默认使用,则返回所选文本的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);
Run Code Online (Sandbox Code Playgroud)
然后你将它添加到你的manifest.json:
"permissions": ["*://*/*"],
"content_scripts": [
{
"matches": ["*://*/*"],
"js": ["/path/to/save_last_element.js"],
"run_at": "document_idle",
"all_frames": true
}
]
Run Code Online (Sandbox Code Playgroud)
现在,当在页面中注入脚本时,您将能够使用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
});
});
Run Code Online (Sandbox Code Playgroud)
请注意,上下文菜单正在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
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
849 次 |
| 最近记录: |