【问题标题】:postMessage is not working with dynamically added iframe in firefox addon using xulpostMessage 不适用于使用 xul 在 Firefox 插件中动态添加的 iframe
【发布时间】:2016-11-22 07:36:35
【问题描述】:

我正在使用 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 插件中接收消息。

有人可以帮忙吗?

【问题讨论】:

  • 我们需要知道你的第一个代码块中的window 是什么(即你做了var window = ??what??;)和你的第二个代码块中的parent
  • 仅供参考:如果您使用的 HTML 文件不是随您的插件提供的(即来自基于 Web 的源)用于您的部分用户界面。
  • 请提供您的 HTML 文件(或至少一个有您的按钮的文件),以便我们拥有测试所需的代码(即 minimal reproducible example)。
  • 另外,请提供您的receiveMessage 功能。

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


【解决方案1】:

解决办法是:

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

这个脚本可以在页面添加动态 iframe 后添加。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-14
    • 2014-02-28
    • 1970-01-01
    相关资源
    最近更新 更多