postMessage无法使用xul

时间:2016-11-22 07:36:36

标签: javascript firefox iframe firefox-addon-sdk xul

我正在使用xul创建一个firefox插件。我使用以下脚本添加了动态iframe:

//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);

以上脚本在页面上成功添加了新的iframe。现在我想从iframe接收消息到我的插件。我在iframe脚本中创建了一个postMessage事件,脚本如下:

//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>

但是我无法在我的firefox插件中收到消息。

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

解决方案是:

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

只需在页面上添加动态iframe后即可添加此脚本。