0

I am working on some experiments that requires to auto generate IDs for elements, I have decided to go with chrome extension.

However, the content script only got triggered when I land on the homepage of the site (e.g. https://secure.checkout.visa.com/). Once I navigate to other pages (e.g. tap on "Create Account"), the script didn't get triggered, I tried to set a break point on the content script but it only got hit on the home page, but not on create account page.

Any idea what went wrong here? Below is the code:

// manifest.json
{
    "manifest_version": 2,
    "name": "Chrome Auto Gen ID",
    "description": "Generate IDs",
    "version": "1.0",

    "permissions": ["activeTab"],

    "background": {
        "scripts": ["event_page.js"],
        "persistent": false
    },

    "browser_action": {
        "default_title": "Auto generate ID"
    },

    "content_scripts": [
        {
            "matches": ["https://secure.checkout.visa.com/*"],
            "js": ["jquery-3.2.1.min.js", "auto_gen_id.js"],
            "all_frames": true,
            "run_at": "document_idle"
        }
    ]
}

The content script:

// auto_gen_id.js
var divs = document.getElementsByTagName("div");
var inputs = document.getElementsByTagName("input");
var sections = document.getElementsByTagName("section");
var count = 0;

function genId(list) {
    for (var i = 0; i < list.length; ++i) {
        var element = list[i];
        if (element.hasAttribute("id")) {
            continue;
        }
        element.id = "gen-id-" + count++;
    }
}

genId(divs);
genId(inputs);

The background script:

// event_page.js
chrome.browserAction.onClicked.addListener(function(tab) {
    console.log('Generating IDs on ' + tab.url);
    chrome.tabs.executeScript(null, {file: "auto_gen_id.js"});
});
Kane Ho
  • 119
  • 2
  • 8
  • 1
    It sounds like the page you are trying to modify is a "single page website". This means that it uses only a single actual page and AJAX to load new content rather than actually loading new pages. I'm not going to go to the site to confirm, but your problem is typical of such pages. See: [Is there a JavaScript/jQuery DOM change listener?](https://stackoverflow.com/a/39508954) for ways to detect when the page changes. – Makyen Aug 24 '17 at 01:33
  • In addition to the above comment, you inject content script two times - on click and via the declaration in manifest.json which automatically runs specified content scripts. – wOxxOm Aug 24 '17 at 04:58

1 Answers1

0

Thanks @makyen and @wOxxOm, followed the suggestions below to solve the problem:

Is there a JavaScript/jQuery DOM change listener

Kane Ho
  • 119
  • 2
  • 8