Javascript 如何获取DOM元素的js路径?

Javascript 如何获取DOM元素的js路径?,javascript,dom,Javascript,Dom,我想记录web应用程序用户的所有交互,以便分析他们如何使用该应用程序。在第一次尝试中,我只想存储单击的任何元素的js路径。JSPath与JSON的关系就像XPath与xml的关系一样 在Chromium浏览器上,您可以获得元素的js路径:只需打开de dev tools(F12),选择“元素”选项卡(第一个),右键单击DOM中的节点,然后选择Copy>Copy js path。您将在剪贴板中获得元素的JS路径,类似于: document.querySelector("#how-to-f

我想记录web应用程序用户的所有交互,以便分析他们如何使用该应用程序。在第一次尝试中,我只想存储单击的任何元素的js路径。JSPath与JSON的关系就像XPath与xml的关系一样

在Chromium浏览器上,您可以获得元素的js路径:只需打开de dev tools(F12),选择“元素”选项卡(第一个),右键单击DOM中的节点,然后选择Copy>Copy js path。您将在剪贴板中获得元素的JS路径,类似于:

document.querySelector("#how-to-format > div.s-sidebarwidget--content.d-block > div:nth-child(5) > span:nth-child(4)")

如果您在控制台中pase上述代码,您将获得对所选节点的引用。如果应用程序包含web组件,因此JSPath包含shadowRoot选择器来遍历dom以到达元素,那么它特别有用:

document.querySelector("#one").shadowRoot.querySelector("div > div")

在第一次尝试中,我想我可以只监听dom中的任何单击,然后记录得到单击的元素的jspath


 document.addEventListener('click', function (event){
   //Get the jspath of the element

});

有没有简单的方法可以获取事件目标的jspath


谢谢

经过一些研究,我在npm或github中找不到任何库,也没有在stackoverflow中找到一个响应,提供了我所期望的,所以我决定实现它。下面我粘贴了一个简单的typescript模块,它实现了这一点。最难的事情是处理插槽

//last 3 elements are window, document and html nodes. We don't need them
function shouldDismiss(tg): boolean {
    return tg === window || tg === document || tg?.nodeName == 'HTML';
}

function isSlot(tg): boolean {
    return tg?.nodeName === 'SLOT';
}

function isDocumentFragment(node): boolean {
    return node?.nodeName === '#document-fragment';
}

function getNodeId(node) {
    return node.id ? `#${node.id}` : ''
}

function getNodeClass(node) {
    if (!node?.classList)
        return '';
    let classes = '';
    for (let cssClass of node.classList)
        classes += `.${cssClass}`
    return classes;
}

function getNodeSelector(node) {
    return `${node.localName || node.nodeName}${getNodeId(node)}${getNodeClass(node)}`
}

export function getEventJSPath(event: Event): string {
    const path = event.composedPath();

    let inSlot = false;
    let jsPath = path.reduce((previousValue: string, currentValue: any) => {
        if (shouldDismiss(currentValue))
            return previousValue;
        if (isSlot(currentValue)) {
            inSlot = true;
            return previousValue
        }
        if (inSlot) {
            if (isDocumentFragment(currentValue))
                inSlot = false;
            return previousValue;
        }
        if (isDocumentFragment(currentValue))
            return previousValue;
        const selector = `.querySelector("${getNodeSelector(currentValue)}")${previousValue}`;

        //if parent node is a document fragment we need to query its shadowRoot
        return isDocumentFragment(currentValue?.parentNode) ? '.shadowRoot' + selector : selector
    }, '');
    jsPath = 'document' + jsPath;

    //Check success on non production environments
    if (process?.env != 'prod') {
        try {
            const el = eval(jsPath);
            if (el != path[0]) {
                debugger;
                console.error('js path error');
            }
        }
        catch (e) {
            debugger;
            console.error('js path error: ' + e.toString());
        }

    }
    return jsPath;
}



请访问,看看有什么和。做一些研究,搜索相关话题等;如果您被卡住了,请发布您的尝试,记录输入和预期输出,最好是在一个什么是jspath?jspath是一个DSL,它允许在JSON文档中导航和查找数据。jspath与json的关系就像xpath与xml的关系一样。在chrome上,您可以打开开发者工具,在“元素”选项卡中选择一个节点,右键单击并复制>复制JS路径以获取该元素的jspath。然后可以在控制台中粘贴所选内容,得到相同的元素。