How can I make a firefox add-on contentscript inject and run a script before other page scripts? -
i'm working on browser extension/add-on. have working in chrome, i'm trying working in firefox.
i've gotten add-on load in firefox developer edition 49.0a2 (2016-07-25).
my extension involves content_script set run_at: document_start
, can inject script tag before other page scripts run, can make object globally available websites.
this has seemed work fine in chrome, in firefox has proven bit of race condition, other page resources loading first of time.
is there strategy load content script in way can inject & load script before other page scripts run?
when add logs, can isolate happening pretty nicely. in example content-script:
// inject in-page script console.log('step 1, happens first') var scripttag = document.createelement('script') scripttag.src = chrome.extension.geturl('scripts/inpage.js') scripttag.onload = function () { this.parentnode.removechild(this) } var container = document.head || document.documentelement // append first child container.insertbefore(scripttag, container.children[0])
now if file scripts/inpage.js
runs log, like
console.log('step 2, should run second')
and visit page script this:
console.log('step 3, page itself, should run last')
in practice, step 2 , step 3 run in non-deterministic order.
thanks lot!
i have firefox-compatible version of script in public repository on special branch if dare try yourself: https://github.com/metamask/metamask-plugin/tree/firefoxcompatibility
an dynamically inserted script external source (<script src>
) not block execution of scripts, there no guarantee script load. if extension worked in chrome, sheer luck.
if want run script before rest, have run inline:
var actualcode = ` // content of scripts/inpage.js here `; var s = document.createelement('script'); s.textcontent = actualcode; (document.head || document.documentelement).appendchild(s); s.remove();
ideally, build script read scripts/inpage.js
, serialize string , put in actualcode
variable. if inpage.js
few lines of code, above can used.
note should not inject code in web page unless absolutely necessary. reason execution environment of page untrusted. if inject @ document_start
, can save functions , (prototype) methods use later (in closure), careful coding required.
if content script not generated build script , still want keep scripts separate, can use synchronous xmlhttprequest
fetch script. synchronous xhr deprecated performance reasons, use @ own risk. extension code typically bundled extension, use of sync xhr should low-risk:
// note: not use synchronous xhr in production! var x = new xmlhttprequest(); x.open('get', chrome.runtime.geturl('scripts/inpage.js'), false); x.send(); var actualcode = x.responsetext; var s = document.createelement('script'); s.textcontent = actualcode; (document.head || document.documentelement).appendchild(s); s.remove();
Comments
Post a Comment