javascript - Chrome Extension content script on iframe without src attribute -


i have content script injecting iframe page's dom. iframe not have src attribute, creating dynamically it's content's like...

iframe.src = 'data:text/html;charset=utf-8,' + encodeuri(html); 

how can run content script on iframe? or communicate background? need trigger "close iframe" event code. know possible because honey doing this.

https://chrome.google.com/webstore/detail/honey/bmnlcjabgnpnenekpadlanbbkooimhnj?hl=en-us

you cannot run content script in frame @ data:-url (crbug.com/55084).

there alternatives though:

  1. in page embeds frame, use onmessage event subscribe events iframe, , insert script in data-url frame calls parent.postmessage.

    // content script in parent frame. // assuming variable iframe exists, , iframe. window.addeventlistener('message', onmessage); function onmessage(event) {     if (event.source === iframe && event.message === 'close') {         window.removeeventlistener('message', onmessage); // clean-up         iframe.remove();     } }  // in iframe parent.postmessage('close'); 
  2. use .srcdoc instead of .src+data urls load html in iframe:

    iframe.srcdoc = html; 

    the html @ same origin parent document, content within frame can use frameelement.remove(); remove frame (example). since script can directly access parent page, html insert must trustworthy. not insert arbitrary html untrusted sites!

  3. declare extension page in web_accessible_resources, , load extension page in frame. can use extension messaging apis communicate between frame , background of extension. unlike previous methods, code in page runs in origin of extension, have access chrome apis (including extension messaging or chrome.storage) , origin-specific data (such localstorage).

    iframe.src = chrome.runtime.geturl('name_of_your_page.html'); 

Comments

Popular posts from this blog

OpenCV OpenCL: Convert Mat to Bitmap in JNI Layer for Android -

android - org.xmlpull.v1.XmlPullParserException: expected: START_TAG {http://schemas.xmlsoap.org/soap/envelope/}Envelope -

python - How to remove the Xframe Options header in django? -