Search code examples
javascriptjquerygoogle-chrome-extension

Get element under mouse on click


I am building a Chrome extension and my goal is the following:

Once a user Ctrl clicks on a username on Reddit, I would like to capture that username on my content script page and send it over to my background page.

Here is how the html in reddit looks like for a random user, the class name is not consistent, so i can not use that.

<a class="s1vhwcq3-4 eTpNeg s1461iz-1 gWXVVu" href="/user/strasse86">u/strasse86</a>

So far I have being experimenting with the onmouseover just trying to capture the username but without success, since it always returns the first captured result.

window.onmouseover=function(e) {

    var href = document.getElementsByClassName(e.target.className[i].href);

    if ( typeof href != "undefined") {
        if (href.includes("https://www.reddit.com/user/")){
                     // do more actions..
        }
    }   
 };

Any ideas please ?


Solution

  • I'm not sure if this is going to help but this is at least something you can look at.

        window.onmouseover=function(e) {
    
            var href = e.target.href;
    
            if ( href) {
                if (href.includes("https://www.reddit.com/user/")){
        		console.log('Contains reddit');
                } else {
        		console.log('Does not contain reddit');
        	    }
            }   
         };
        <a class="s1vhwcq3-4 eTpNeg s1461iz-1 gWXVVu" href="/user/strasse86">u/strasse86</a>
      <a class="s1vhwcq3-4 eTpNeg s1461iz-1 gWXVVu" href="/user/strasse87">u/strasse87</a>
      <a class="s1vhwcq3-4 eTpNeg s1461iz-1 gWXVVu" href="https://www.reddit.com/user/strasse88">u/strasse88</a>