【问题标题】:Detect ajax page changes and add components with DOM (Chrome Extensions, JavaScript)检测 ajax 页面更改并使用 DOM(Chrome 扩展、JavaScript)添加组件
【发布时间】:2021-10-05 12:03:58
【问题描述】:

我正在尝试将 DOM 元素添加到页面 https://anilist.co/user/diskxo/animelist

var divEntryRow = document.getElementsByClassName("entry row")[x]
    var playbutton = document.createElement("DIV");
    playbutton.className = "playbutton";
    var aInput = document.createElement("A");
    var img = document.createElement("IMG");   
    aInput.appendChild(img);
    playbutton.appendChild(aInput);
    divEntryRow.appendChild(playbutton);

,但加载时不会显示整个页面,所以我的扩展程序没有 在某些地方添加元素(右侧播放按钮)

此外,当我在站点的选项卡之间移动时,不会重新加载扩展程序,因为仅通过 ajax 在后台进行更新。我一直在寻找检测更改并重新加载扩展程序的方法,包括:

$.ajax({
    processData: false,
    contentType: false,
    success: function() {
        doThings();
       
    },
});

或者:

function DOMModificationHandler(){
    $(this).unbind('DOMSubtreeModified.event1');
    setTimeout(function(){
        doThings();
        $('#ContentContainer').bind('DOMSubtreeModified.event1',DOMModificationHandler);
    },1000);
}

//after document-load
$('#ContentContainer').bind('DOMSubtreeModified.event1',DOMModificationHandler);

我在我的扩展中包含了 jquery 库。这是我的 manifest.json 文件:

{
    "manifest_version": 2,
    "name": "JiyuMe",
    "version": "1.0",

    "description": "Your next anime streaming website... it's not a streaming website!",

    "content_scripts": [{
        "matches": ["*://*.anilist.co/*"],
        "js": ["js/jquery-3.6.0.min.js", "js/client.js"]
    }],

    "background": {
        "scripts": ["js/background.js"]
    },

    "browser_action": {
        "default_popup": "popup.html"
    },

    "permissions": [
        "*://anilist.co/*",
        "nativeMessaging",
        "tabs",
        "activeTab"
    ],
    "content_security_policy": "script-src 'self' https://apis.google.com; object-src 'self'"

}

您有什么想法可以解决这个问题吗?

【问题讨论】:

    标签: javascript ajax dom google-chrome-extension


    【解决方案1】:

    对于第二个问题,我用一个简单的函数解决了:

    //Sleep function
    function sleep(ms) {
        return new Promise((resolve) => setTimeout(resolve, ms));
    }
    
    //Wait for Ajax site load
    $.ajax({
        processData: false,
        contentType: false,
        success: async function() {
            onPageChange("1");
        },
    });
    
    async function onPageChange(oldPage_val) {
        var currentPage = window.location.href;
        if (currentPage != oldPage_val) {
            oldPage_val = currentPage;
            pageScan();
            await sleep(500);
            onPageChange(oldPage_val);
        } else {
            await sleep(500);
            onPageChange(oldPage_val);
        }
    }
    

    我等待页面加载,然后启动 onPageChange() 函数,该函数每 500 毫秒检查一次页面链接是否更改。 借助变量将旧链接与新链接进行比较:oldPage_val

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-24
      • 1970-01-01
      • 1970-01-01
      • 2016-03-31
      • 2018-04-02
      • 2012-03-14
      • 1970-01-01
      相关资源
      最近更新 更多