0

The following works fine. I click #testlink and it fires.

jQuery(document).ready(function() {
    jQuery("#testlink").on("click", function(event) {
        document.dispatchEvent(new CustomEvent('funcTest', {
            'detail': {
                test: 'stuff'
            }
        }));
    });
});

Now I want to do the same thing without an on.click, I want it to fire when the web page loads. So remove the onclick.

jQuery(document).ready(function() {
    document.dispatchEvent(new CustomEvent('funcTest', {
        'detail': {
            test: 'stuff'
        }
    }));
});

But it doesn't work. Nothing happens. Why? How can I get this to fire when the page loads?

Krupesh Kotecha
  • 2,396
  • 3
  • 21
  • 40
Ken Williams
  • 829
  • 1
  • 10
  • 20
  • The code should work: https://jsfiddle.net/a87umsjh/ - Is the event handler for `funcTest` assigned before the `dispatchEvent` call? – Andreas May 17 '16 at 07:42
  • yes, I think that is what is happening. funcTest is actually in a content.js which is part of a Chrome extension. its in a different sandbox. so it must be getting assigned too late? how would I fix that? I'll try a setTimeout which I think is stupid. – Ken Williams May 17 '16 at 21:40
  • ya, it works with a setTimeout. Even if the timeout is super low like 2 or 10. but as soon as I comment out the timeout it doesn't fire anymore. I think setTimeout is ugly. there has to be a better way to call funcTest without having to wait. – Ken Williams May 17 '16 at 21:55
  • I haven't done anything yet with chrome extensions... Maybe [this post](http://stackoverflow.com/questions/5113318/in-a-chrome-extension-content-script-must-i-wait-for-document-ready-before-proc) can help – Andreas May 18 '16 at 05:44
  • Thanks, it did help. "run_at": "document_start" did it in the manifest. – Ken Williams May 18 '16 at 06:22

1 Answers1

0

Adding "run_at": "document_start" in the manifest for some reason makes the content script load faster.

Ken Williams
  • 829
  • 1
  • 10
  • 20