Есть ли работающее автоматическое изменение размера междоменного окна iframe?

Вы могли использовать DATE_FORMAT для извлечения частей дня и месяца дат дня рождения.

РЕДАКТИРОВАНИЕ: извините я не видел, что он не использовал MySQL.

95
задан DRosenfeld 5 November 2015 в 13:21
поделиться

1 ответ

Я столкнулся с этой проблемой при работе над чем-то на работе (использование Реагируют). В основном у нас есть некоторое внешнее содержимое HTML, которое мы сохраняем в нашу таблицу документа в базе данных и затем вставляем на страницу при определенных обстоятельствах, когда Вы находитесь в наборе данных Документов.

Так, учитывая n встраивает, которых [до 113] могли содержать внешний HTML, мы должны были создать систему для автоматического изменения размеров iframe каждого, встраивают однажды содержание, полностью загруженное в каждом. После вращения моих колес некоторое время, это - то, как я закончил тем, что делал его:

  1. Набор message слушатель события в индексе нашего Реагировать приложение, которое проверяет на определенный ключ, который мы установим от отправителя iframe.
  2. В компоненте, который на самом деле представляет iframes после вставки внешнего HTML в него, я добавляю <script> тег, который будет ожидать iframe's window.onload для увольнения. Как только это стреляет, мы используем postMessage для отправки сообщения в родительское окно с информацией о iframe идентификаторе, вычисленной высоте, и т.д.
  3. , Если соответствия источника и ключ удовлетворены в индексном слушателе, захватите DOM id iframe, который мы передаем в MessageEvent объект
  4. , Как только мы имеем эти iframe, просто устанавливаем высоту от значения, которое передается от iframe postMessage.
// index
if (window.postMessage) {
    window.addEventListener("message", (messageEvent) => {
        if (
            messageEvent.data.origin &&
            messageEvent.data.origin === "company-name-iframe"
        ) {
            const iframe = document.getElementById(messageEvent.data.id)
            // this is the only way to ensure that the height of the iframe container matches its body height
            iframe.style.height = `${messageEvent.data.height}px`
            // by default, the iframe will not expand to fill the width of its parent
            iframe.style.width = "100%"
            // the iframe should take precedence over all pointer events of its immediate parent
            // (you can still click around the iframe to segue, for example, but all content of the iframe
            // will act like it has been directly inserted into the DOM)
            iframe.style.pointerEvents = "all"
            // by default, iframes have an ugly web-1.0 border
            iframe.style.border = "none"
        }
    })
}
// in component that renders n iframes
<iframe
    id={`${props.id}-iframe`}
    src={(() => {
        const html = [`data:text/html,${encodeURIComponent(props.thirdLineData)}`]
        if (window.parent.postMessage) {
            html.push(
                `
                <script>
                window.onload = function(event) {
                    window.parent.postMessage(
                        {
                            height: document.body.scrollHeight,
                            id: "${props.id}-iframe",
                            origin: "company-name-iframe",
                        },
                        "${window.location.origin}"
                    );
                };
                </script>
                `
            )
        }

        return html.join("\n")
    })()}
    onLoad={(event) => {
        // if the browser does not enforce a cross-origin policy,
        // then just access the height directly instead
        try {
            const { target } = event
            const contentDocument = (
                target.contentDocument ||
                // Earlier versions of IE or IE8+ where !DOCTYPE is not specified
                target.contentWindow.document
            )
            if (contentDocument) {
                target.style.height = `${contentDocument.body.scrollHeight}px`
            }
        } catch (error) {
            const expectedError = (
                `Blocked a frame with origin "${window.location.origin}" ` +
                `from accessing a cross-origin frame.`
            )
            if (error.message !== expectedError) {
                /* eslint-disable no-console */
                console.err(
                    `An error (${error.message}) ocurred while trying to check to see ` +
                    "if the inner iframe is accessible or not depending " +
                    "on the browser cross-origin policy"
                )
            }
        }
    }}
/>
0
ответ дан 24 November 2019 в 05:53
поделиться