How do you detect that a script was loaded *and* executed in a chrome extension? -
i've been tracking down bug days... realized bug me. :/
i had been using webrequest.oncomplete, filtered scripts. error made incorrect association between scripts being loaded , being executed. loaded in different order executed, , timing of events not in order need them in. need inject between scripts need event right after file has been executed , before next one.
the solution can think of @ moment alter js being loaded before gets executed. makes stomach turn. , bfcache wreak more havoc, not great solution either.
i use html5 spec's afterscriptexecute, not implemented in chrome. there api, perhaps extension api can use?
note: method no longer works of chrome 36. there no direct alternatives.
note: answer below applies external scripts, i.e. loaded <script src>
.
in chrome (and safari), "beforeload" event triggered right before resource loaded. event allows 1 block resource, script never fetched. in event, can determine whether loaded resource script, , check whether want perform action
this event can used emulate beforescriptexecute / afterscriptexecute:
document.addeventlistener('beforeload', function(event) { var target = event.target; if (target.nodename.touppercase() !== 'script') return; var dispatchevent = function(name, bubbles, cancelable) { var evt = new customevent(name, { bubbles: bubbles, cancelable: cancelable }); target.dispatchevent(evt); if (evt.defaultprevented) { event.preventdefault(); } }; var onload = function() { cleanup(); dispatchevent('afterscriptexecute', true, false); }; var cleanup = function() { target.removeeventlistener('load', onload, true); target.removeeventlistener('error', cleanup, true); } target.addeventlistener('error', cleanup, true); target.addeventlistener('load', onload, true); dispatchevent('beforescriptexecute', true, true); }, true);
the dispatch times not 100% identical original ones, sufficient cases. time line (non-emulated) events:
beforeload before network request started beforescriptexecute before script executes afterscriptexecute after script executes onload after script has executed
here's easy way see events working expected:
window.addeventlistener('afterscriptexecute', function() { alert(window.x); }); document.head.appendchild(document.createelement('script')).src = 'data:,x=1'; document.head.appendchild(document.createelement('script')).src = 'data:,x=2';
the demo can seen live @ http://jsfiddle.net/sdazt/
Comments
Post a Comment