简体   繁体   中英

DOM nodes null in chrome extension content script

I have a chrome extension where I'm trying to navigate the DOM beginning at the clicked element, with the following content script:

document.addEventListener("mousedown", function(event) {

    const selection = window.getSelection();
    console.log(selection);
    const currentNode = selection.anchorNode;
    console.log(currentNode);​
}

On the first click, currentNode is always null. On subsequent clicks it is the selected node, as expected.

In the debug window the logged selection variable shows the selection object with all members null, but they are evaluated if I expand the object with the drop down arrow next to it.

It looks like something is being asynchronously evaluated, which I gather is usually handled with promises in JavaScript. Neither of the calls I make return a promise that I can wait on though.

Am I missing something obvious here? How do I force evaluation of the selection's members the first time round?

I think the issue here is that the mousedown event is firing too early.

Try changing it to a click or mouseup event instead of mousedown .

Also, on a click event you have access to event.target , which will be the node that was clicked on. window.getSelection() is probably not what you're looking for here if your goal is simply to navigate starting from the clicked element.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM