首页 > 解决方案 > 在页面上多次使用 iframe 时出现问题

问题描述

我正在创建一个快速查看功能,您可以在其中直接在将打开的模式中查看产品列表中每个项目的内容。

在模态中有一个用javascript动态生成的框架,我放置了呈现模态内容的控制器的url(这样的url http://localhost/quickview/product/view/id/18564/)。

当模态关闭时,我删除模态内容,当用户想在同一页面上看到另一个产品的内容时,我用javascript重新生成一个iframe元素并显示。

问题是在第一个模态视图之后,iframe 再次加载并显示内容,但是在 iframe 中运行的 javascript(我们在产品内容中有一个图片库)不起作用。在画廊前面的第二次尝试后不久,所有其他使用 javascript 的行为都不起作用,尽管来自控制器的模态、iframe 和内容是正确的。

我已经尝试重新加载相同的 iframe(不破坏它)并再次显示它,我尝试创建 id 与每个模式视图不同的 iframe,但我无法解决一次。在我用来生成模态和 iframe 的 javascript 下面。我认为不相关的控制器(每当我在新选项卡中打开内容的 url 时,一切正常,并且每次我首先打开模态时都独立于产品,一切都在模态中正确加载)。

var ProductInfo = Class.create();
ProductInfo.prototype = {
    settings: {
        'loadingMessage': 'aguarde ...',
        'viewport': document.viewport.getDimensions()
    },

    idframe: 'quick-frame',

    initialize: function(selector, x_image, settings) {
        Object.extend(this.settings, settings);
        this.createWindow();

        var that = this;
        $$(selector).each(function(el, index){
            el.observe('click', that.loadInfo.bind(that));
        })

    },

    createLoader: function() {
        var loader = new Element('div', {id: 'pleaseWaitDialog'});
        var imgLoader = new Element('img', {src: '/js/inovarti/ajax-loader.gif', alt: this.settings.loadingMessage, id: 'loading-quickview-img'});
        var contentLoader = new Element('p', {class: 'loader'});

        contentLoader.setStyle({
            'display': 'block',
            'margin-top': (this.settings.viewport.height/2 - contentLoader.getHeight()/2)+'px',
            'text-align': 'center'
        });

        contentLoader.appendChild(imgLoader);
        loader.appendChild(contentLoader);
        document.body.appendChild(loader);

        $('pleaseWaitDialog').setStyle({
            'position': 'fixed',
            'top':  0,
            'left':  0,
            'width': '100%',
            'height': '100%',
            'display': 'block',
            'opacity': '.8',
            'background': '#FFFFFF',
            'z-index': '99999'
        });
    },

    destroyLoader: function(full) {
        if(full) {
            $('pleaseWaitDialog').remove();
        }
        else {
            if($('loading-quickview-img') != null) {
                $('loading-quickview-img').remove();
            }
            $('pleaseWaitDialog').setStyle({'background-color': '#000000'});
        }
    },

    showButton: function(e) {
        el = this;
        while (el.tagName != 'P') {
            el = el.up();
        }
        $(el).getElementsBySelector('.quickview-ajax')[0].setStyle({
            display: 'block'
        })
    },

    hideButton: function(e) {
        el = this;
        while (el.tagName != 'P') {
            el = el.up();
        }
        $(el).getElementsBySelector('.quickview-ajax')[0].setStyle({
            display: 'none'
        })
    },

    createWindow: function() {
        var qWindow = new Element('div', {id: 'quick-window'});
        qWindow.innerHTML = '<div id="quickview-header" style="width: 100%; text-align: right;"><a href="javascript:void(0)" id="quickview-close"><i class="glyphicon glyphicon-remove"></i></a></div><div class="quick-view-content"></div>';
        document.body.appendChild(qWindow);
        $('quickview-close').setStyle({
            'padding-right': "20px",
            'padding-left': "20px"
        });
        $('quickview-close').observe('click', this.hideWindow.bind(this));
    },

    showWindow: function() {
        var screenWidth, offsetTopModal;
        if(document.body.clientWidth > 1400) {
            screenWidth = 1400;
            offsetTopModal = 100;
        }
        else {
            if(document.body.clientWidth < 768) {
                screenWidth = document.body.clientWidth;
                offsetTopModal = 0;
            }
            else {
                screenWidth = document.body.clientWidth * 0.8;
                offsetTopModal = 100;
            }
        }

        var windowWidth = screenWidth;

        $('quick-window').setStyle({
            'top':  document.viewport.getScrollOffsets().top + offsetTopModal + 'px',
            'left':  document.body.clientWidth/2 - windowWidth/2 + 'px',
            'display': 'block',
            'position': 'absolute',
            'width': windowWidth + 'px',
            'background': '#FFFFFF',
            'padding': '20px 0px',
            'margin-bottom': '20px',
            'border': '1px solid #F0F0F0',
            'z-index': '999999',
            'border-radius': '4px'
        });

        $('pleaseWaitDialog').observe('click', this.hideWindow.bind(this));

        this.resizeIframe($(this.idframe));
    },

    setContent: function(srcUrl) {
        var options = {
            id: this.idframe,
            frameborder: "0",
            scrolling: "no",
            src: srcUrl,
            hspace: "0",
            name: this.idframe+(new Date().getTime()),
            width: "100%"
        };
        var frame = new Element('iframe', options);
        $$('.quick-view-content')[0].insert(frame);
    },

    clearContent: function() {
        $$('.quick-view-content')[0].replace('<div class="quick-view-content"></div>');
    },

    hideWindow: function() {
        this.clearContent();
        this.destroyLoader(true);
        $('quick-window').hide();
    },

    loadInfo: function(e) {
        e.stop();
        var that = this;
        this.createLoader();
        this.clearContent();
        this.setContent(e.element().href);

        Event.observe($(this.idframe), 'load', function() {
            window.quickview.completeInfo();

            setTimeout(function () {
                window.quickview.resizeIframe($(this.idframe));
            },500);
        });
    },

    completeInfo: function () {
        this.destroyLoader(false);
        this.showWindow();
    },

    resizeIframe: function(obj) {
        if(obj) {
            obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px';
            obj.style.width = "100%";
        }
    }
}

Event.observe(window, 'load', function() {
    window.quickview = new ProductInfo('.quickview-ajax', '.product-image', {
    });
});

我认为这无关紧要,但应用程序是 Magento 1.9.3.9,所以我使用原型作为 js 框架(来自 Magento 的原生)。

一个奇怪的事实是,如果我通过浏览器使用右键更新框架并使用鼠标请求“刷新框架”,则 iframe 会正确更新并且内容 javascript 会正确加载。

更新:

通过执行一些测试,我注意到第一次加载 iframe 时,在 iframe 内的 js 中检测到 iframe 的宽度。但是在创建和插入它的其他时间,宽度被检测为零。下面的测试:

//First open
console.log(document.documentElement.clientWidth);
//output: 1356

//Second open
console.log(document.documentElement.clientWidth);
//output: 0

OwlCarousel2 抛出(更多细节在https://github.com/OwlCarousel2/OwlCarousel2/issues/1704),我认为 de JS 会出现异常。

Owl.prototype.viewport = function() {
    var width;
    if (this.options.responsiveBaseElement !== window) {
        width = $(this.options.responsiveBaseElement).width();
    } else if (window.innerWidth) {
        width = window.innerWidth;
    } else if (document.documentElement && document.documentElement.clientWidth) {
        width = document.documentElement.clientWidth;
    } else {
        throw 'Can not detect viewport width.';
    }
    return width;
};

即使我更改了 OwlCarousel2(最新版本没有抛出),我相信宽度被错误检测的事实会产生其他几个问题。我还通过始终创建 100% 宽来更新 iframe,但问题仍然存在。

标签: javascriptmagentoiframemodal-dialogprototypejs

解决方案


这是一个 jQuery 缓存问题。您应该从服务器发送标头,以免在客户端中缓存 iframe:

Cache-Control: no-cache, no-store, must-revalidate
Pragma: no-cache
Expires: 0

您还可以使用以下命令强制 iframe 刷新:

iframe.contentWindow.location.reload(true);

更新

var nameOrIndex = 'nameOrIndex'; // i.e. 'my_iframe' or '0'
var iFrame = window.frames[nameOrIndex];
if (iFrame) {
    var document = iFrame.contentDocument ? iFrame.contentDocument : iFrame.contentWindow ? iFrame.contentWindow.document : iFrame.document;
    if (document && document.location) {
        document.location.reload(true); // 1 (sandboxing, same domain origin policy)
        document.location.href = document.location.href; // 2 (cross domain, might detect size changes)
    }
    if (iFrame.src) {
        window.frames[nameOrIndex].src = iFrame.src; // 3 (cross domain, might detect size changes)
    }
    $(iFrame).replaceWith($(iFrame).clone()); // 4 (cross domain, might detect size changes)
}

但是,关于您的尺寸问题,请查看此SO question


推荐阅读