当前位置: 代码迷 >> JavaScript >> chrome扩展程序,将数据传递到iframe
  详细解决方案

chrome扩展程序,将数据传递到iframe

热度:72   发布时间:2023-06-12 14:09:43.0

似乎以前有人问过这个问题,但我无法使其正常工作。 我的问题是

我想创建一个包含IFrame的弹出对话框(如果存在更好的主意,则可以进行类似操作)。 将会发生的情况是,用户将右键单击并调用“使申请者”,我要获取用户所在的页面,并将其发送到iframe,iframe将在其中进行解析,显示结果,然后用户选择编辑和/或保存申请人。

在这种情况下,我得到以下错误:

运行时事件处理程序中的错误。onMessage:DataCloneError:无法在“ Window”上执行“ postMessage”:无法克隆HTMLBodyElement对象。 在chrome.runtime.onMessage.addListener.request(chrome-extension://ljkbppmibpdchehdfdhijcoaenhnblhm/content.js:16:30)

我不确定如何实现:将innerHTML传递给iframe进行解析和显示。

background.js

chrome.contextMenus.create({ 
    contexts: ['all'],
    id: 'applicantParser',
    title: 'Make Applicant'
  });

chrome.contextMenus.onClicked.addListener(() => {
    chrome.tabs.query({active: true, currentWindow: true}, tabs => {
        chrome.tabs.sendMessage(tabs[0].id, {type: 'requestParseApplicant'});
    });
});

的manifest.json

{
    "name": "TW Extension",
    "description" : "TW Extension",
    "icons": { 
      "16": "icon-16.png"
    },
    "version": "1.0",
    "manifest_version": 2,
    "browser_action" :
    {
        "default_icon" : "icon-16.png",
        "default_popup": "index.html"
    },
    "content_scripts": [{
      "js": [ "content.js"],
      "matches": [ "<all_urls>"],
      "all_frames": true
     }],
     "background": {
      "scripts": ["background.js"]
     },
     "permissions": ["contextMenus", "storage", "activeTab", "debugger"],
     "web_accessible_resources" : ["index.html", "x.js"]
  }

content.js

chrome.runtime.onMessage.addListener(request => {
    console.log( request );
    console.log(document.body.innerHTML);
    if (request.type === 'requestParseApplicant') {
        var bodyHtml = "<dialog style='height:70%; width:50%;'>";
        bodyHtml += "<iframe id='parseApplicant' style='height:100%'></iframe>";
        bodyHtml += "<div style='position:absolute; top:0px; left:5px;'><button>x</button></div>";
        bodyHtml += "</dialog>";
        document.body.innerHTML +=  bodyHtml;

        const dialog = document.querySelector("dialog");
        dialog.showModal();
        const iframe = document.getElementById("parseApplicant");  
        //iframe.src = chrome.extension.getURL("index.html");
        iframe.src = chrome.runtime.getURL("index.html");
        iframe.contentWindow.postMessage({call:'sendValue', value: document.body});
        iframe.frameBorder = 0;        
        dialog.querySelector("button").addEventListener("click", () => {
            dialog.close();
        });
    }
}); 

跟随wOxxOm提供的注释,还需要为原点添加“ *”

const iframe = document.getElementById("parseApplicant");  
iframe.src = chrome.runtime.getURL("index.html");

iframe.onload = () => { 
    iframe.contentWindow.postMessage({call:'sendValue', value: innerHtml}, "*"); 
}

iframe.frameBorder = 0;      

在以下位置找到原因: :

  相关解决方案