简体   繁体   中英

Getting element in DOM after ajax call

There is a lot question and answers about that question, but I'm not being able to make it work for my case.

My extension gets the positions (1,2,...,100) on the scores pages of a game. When I first load the page I get the first 100 positions, but there are more pages, the problem is that the other pages are called with ajax and I cannot get them after the ajax call.

I came to conclusion that I could use Mutation Observers to detect changes in DOM, but I tried a lot of different codes and they all seem to not work.

My manifest.json file:

{
    "manifest_version": 2,
    "name": "Ogame Fleet Counter",
    "short_name": "OFC",
    "version": "1.0",
    "icons": { "16": "16.png",
               "48": "48.png",
               "128": "128.png"
    },
    "browser_action": {
        "default_icon": "48.png"
    },
    "background": {
        "scripts": ["js/background.js"]
    },
    "content_scripts": [
        {
            "matches":[
                "https://*.ogame.gameforge.com/game/index.php?page=shipyard*",
                "https://*.ogame.gameforge.com/game/index.php?page=highscore"
            ],
            "js": ["js/jquery.js", "js/content.js"] 
        }
    ]
}

My background.js file:

chrome.browserAction.onClicked.addListener(function(tab) {
  chrome.tabs.executeScript(null, { file: "js/jquery.js" }, function() {
    chrome.tabs.executeScript(null, { file: "js/content.js" });
  });
});
var insertedNodes = [];
var observer = new MutationObserver(function(mutations) {
 mutations.forEach(function(mutation) {
   for (var i = 0; i < mutation.addedNodes.length; i++)
     insertedNodes.push(mutation.addedNodes[i]);
 })
});
observer.observe(document, { childList: true });
console.log(insertedNodes);

My extension consists in only background.js , the content.js (content script) and jquery.js .

I tried much more codes and tried changed my own, no luck. Could I use another method than Mutation Observers ? Adding onclick function in all buttons to trigger my content script maybe? Appreciate some help.

Edit: So I saw on the DOM that I need to catch: <span class=" activePager">1</span> changing, the number 1 there represents page one when I click on page two it changes to 2.

You need use your Mutation Observer on content script, because changes are happens there.

After this, you can send these changes to the Background page and process it from there.

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