Greasy Fork is available in English.

Diskuse » Development

iframe

Я пишу пользовательский скрипт для сбора информации с HTML-страницы, но столкнулся с проблемой: часть нужной мне информации находится в iframe. Теперь я не могу получить эти данные с помощью JavaScript. Есть ли решение для данной проблемы?

Когда я выполняю следующий код, я получаю iframe, но значение iframeDocument равно null:

var iframe = document.querySelector('iframe');
console.log(iframe);

var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
console.log(iframeDocument);

  1. Inject your userscript in both iframe window and top window.

  2. Userscript inside iframe window: Grab the information and send to the top window using window.top.postMessage(...)

  3. Userscript inside the top window: window.addEventListener('message', ..., false)

Я получаю "Blocked a frame with origin". Я пытаюсь получить доступ к iframe, находящемся на другом домене. Это вызывает блокировку и выбрасывает исключение DOMException.

// ==UserScript==
// @name         Userscript Communication Demo
// @match        *://*/*
// ==/UserScript==

// Check if the script is running in the top window
if (window.self === window.top) {
    // Execute code in the top window
    console.log("Running in the top window");

    // Send a message to the iframe
    window.addEventListener('message', function(event) {
        if (event.data === 'Hello from iframe') {
            console.log("Received message from iframe:", event.data);
            event.source.postMessage('Hello from top window', event.origin);
        }
    });
} else {
    // Execute code in the iframe
    console.log("Running in an iframe");

    // Send a message to the top window
    window.parent.postMessage('Hello from iframe', '*');

    // Receive message from the top window
    window.addEventListener('message', function(event) {
        if (event.data === 'Hello from top window') {
            console.log("Received message from top window:", event.data);
        }
    });
}

Post reply

Sign in to post a reply.