开发者

Google Chrome Extension: highlight the div that the mouse is hovering over

I am new to Google Chrome extensions and trying to write an extension that highlights a div on hover. If there is a div inside another div and inner div is hovered, I would like to highlight the internal div only.

I have got som开发者_开发百科e of the samples working but I'm not sure how to catch the hover event.


In HTML, every mouse event has access to the underlying element. You can do that easily with JavaScript, and there is a nice feature in HTML5 called classList (thanks to Erik from Chromium) that allows you to add and remove classes from DOM's easily.

First of all, you can achieve this with Google Chrome's Content Scripts. The algorithm is quite straightforward, you keep a pointer to the last visited DOM, and you just add/remove class's when you visit another DIV element.

Within your manifest.json We will define the CSS and JS injections to every page we see.

 ...
  ...
  "content_scripts": [
    {
      "matches": ["http://*/*"],
      "css": ["core.css"],
      "js": ["core.js"],
      "run_at": "document_end",
      "all_frames": true
    }
  ]
  ...
  ...

Now lets look into our core.js, I have included some comments to explain what is going on:

// Unique ID for the className.
var MOUSE_VISITED_CLASSNAME = 'crx_mouse_visited';

// Previous dom, that we want to track, so we can remove the previous styling.
var prevDOM = null;

// Mouse listener for any move event on the current document.
document.addEventListener('mousemove', function (e) {
  var srcElement = e.srcElement;

  // Lets check if our underlying element is a DIV.
  if (srcElement.nodeName == 'DIV') {

    // For NPE checking, we check safely. We need to remove the class name
    // Since we will be styling the new one after.
    if (prevDOM != null) {
      prevDOM.classList.remove(MOUSE_VISITED_CLASSNAME);
    }

    // Add a visited class name to the element. So we can style it.
    srcElement.classList.add(MOUSE_VISITED_CLASSNAME);

    // The current element is now the previous. So we can remove the class
    // during the next iteration.
    prevDOM = srcElement;
  }
}, false);

Now, lets look at the simple core.css for the styles:

.crx_mouse_visited {
  background-color: #bcd5eb !important;
  outline: 1px solid #5166bb !important;
}

Thats it, you will notice that all your divs will have a "hovered" state, similar on what happens when you visit your browser inspector when inspecting elements.


Now it is 2018, and 7.5 years past since this question was asked. Yet the question is still relevant, and the answer provided by mohamed-mansour is the best.

Yet I wish to optimize it a bit, modernize with support for https, and provide full documentation to the whole Chrome extension.

mannifest.json

{
    "name": "Mark active image",
    "version": "1.11",
    "description": "Mark image with dashed frame.",
    "permissions": [
        "activeTab",
        "declarativeContent"
    ],
     "content_scripts": [
        {
            "matches": [
                "http://*/*",
                "https://*/*"
            ],
            "css": [
                "imageMarker.css"
            ],
            "js": [
                "imageMarker.js"
            ]
        }
    ],
   "manifest_version": 2
}

imageMarker.js

In my example bellow I am marking images (IMG tag) in the page with dashed outline. And avoid redundant processing on the current image.

// Unique ID for the className.
var MOUSE_VISITED_CLASSNAME = 'crx_mouse_visited';

// Previous dom, that we want to track, so we can remove the previous styling.
var prevDOM = null;

// Mouse listener for any move event on the current document.
document.addEventListener('mousemove', function (e) {
    let srcElement = e.srcElement;

    // Lets check if our underlying element is a IMG.
    if (prevDOM != srcElement && srcElement.nodeName == 'IMG') {

        // For NPE checking, we check safely. We need to remove the class name
        // Since we will be styling the new one after.
        if (prevDOM != null) {
            prevDOM.classList.remove(MOUSE_VISITED_CLASSNAME);
        }

        // Add a visited class name to the element. So we can style it.
        srcElement.classList.add(MOUSE_VISITED_CLASSNAME);

        // The current element is now the previous. So we can remove the class
        // during the next ieration.
        prevDOM = srcElement;
        console.info(srcElement.currentSrc);
        console.dir(srcElement);
    }
}, false);

imageMarker.css

.crx_mouse_visited {
    background-clip: #bcd5eb!important;
    outline: 1px dashed #e9af6e!important;
}


@pdknsk What you can do to set this for every element is, for the onload event of the body, run this code:

bod= document.body;
walker = document.createTreeWalker(bod,NodeFilter.SHOW_ELEMENT,null,false);
while (walker.nextNode()){
    walker.currentNode.addEventListener("mouseover",on,false);
    walker.currentNode.addEventListener("mouseout",off,false);
}

and modify on and off like this:

on=function(elem){ oldBG = this.style.backgroundColor;
                   this.style.backgroundColor='#123456';
                   this.addEventListener("mouseout",function(){this.style.backgroundColor= oldBG},false);
}

The thing to notice is that, this will only work if the styling is set using the element.style object, and in order to make it more robust you will need to get the element.style.cssText and process (using regex) and modify it.

All in all, Mohamed Mansour's Answer is the best way to achieve this.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜