简体   繁体   中英

postMessage is not working with dynamically added iframe in firefox addon using xul

I am creating a firefox addon using xul. I have added a dynamic iframe using following script:

//addon script:
let chromeUrl = 'https://myserver/downloadProduct.html';
                        Components.utils.import('resource://gre/modules/Services.jsm');//Services
                        let activeWindow = Services.wm.getMostRecentWindow('navigator:browser');

                        let mainDocument = activeWindow.document;

                        let iframeEl;
                        iframeEl = mainDocument.createElement('iframe');

                        iframeEl.id = "d";
                        iframeEl.setAttribute('src',chromeUrl);
                        iframeEl.setAttribute("tooltip", "aHTMLTooltip");
                        iframeEl.setAttribute("autocompleteenabled", true);
                        iframeEl.setAttribute("autocompletepopup", "PopupAutoComplete");
                        iframeEl.setAttribute("disablehistory",true);
                        iframeEl.setAttribute('type', 'content');
                        iframeEl.setAttribute('height', '32px');


                        window.document.documentElement.insertBefore(iframeEl, window.document.documentElement.window);
window.addEventListener("message", receiveMessage,false);

Above script is successfully adding a new iframe on page. Now I want to receive messages from iframe to my addon. I have created a postMessage event in iframe script, script as follows:

//iFrame Script:
<script type="text/javascript">
        $(document).ready(function () {
            $("#Download").click(function () {
                parent.postMessage({ Action: "DOWNLOADED", Result: null }, "*");
            })

            $("#NotNow").click(function () {
                parent.postMessage({ Action: "NOT_NOW", Result: null }, "*");
            })

            $("#Never").click(function () {
                parent.postMessage({ Action: "DO_NOT_SHOW", Result: null }, "*");
            })
        });
    </script>

But I am not able to receive message in my firefox addon.

Can anybody help?

Solution is:

window.document.getElementById("iframeId").contentWindow.document.getElementById("elementId").addEventListener('click', function() {
                                //Do something
                            }, false);

This script can be added just after adding dynamic iframe on the page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM