0

Мы разрабатываем расширения браузера для Google Chrome, Firefox и Safari. Нам нужно вставить iframe в папку «Входящие» (https://inbox.google.com/) в нашем расширении Chrome. Я создал код JavaScript, который вставляет iframe на страницу с помощью jQuery. Вот код:Как вставить iframe с динамическим источником HTTPS из расширения Chrome?

JavaScript код:

var $container = jQuery('<div id="ws_login_overlay" style="position: absolute; width: 100%; height: 100%; left: 0px; top: 0px; z-index: 9999999; background: rgba(64, 64, 64, 0.8);"></div>'); 
$container.append('<iframe width="760" height="510" id="myframe" style="border: 1px solid grey; margin: 80px auto 0px auto; display: table; border-radius: 8px;" src="'+Utils.getUrl("content/login/login_iframe.html?url="+encodeURIComponent(WS.config.URLs.website.web_login+'#'+reply.ws_uid))+'"></iframe>'); 
jQuery("body").append($container); 

Utils.getUrl = function(filename, preferSecure) { 
    return WS.getURL(filename, preferSecure); 
}; 

/* Function to retrieve the relative URL/URI of a file in the platform's file system. */ 
WS.getURL = function(filename, preferSecure) { 
    if (typeof filename !== "string") { 
     filename = ""; 
    } else if (filename.substr(0, 1) === "/") { /* Remove forward slash if it's the first character, so it matches with the base URLs of the APIs below. */ 
     filename = filename.substr(1); 
    } 

    switch (Sys.platform) { 
     case 'chrome': 
      return chrome.extension.getURL(filename); 
    } 
}; 

login_iframe.html:

<style> 
html, body, iframe { 
    margin: 0; 
    border: 0; 
    padding: 0; 
    display: block; 
} 
</style> 
<script src="login_iframe.js"></script> 
<iframe id="iframe"></iframe> 

login_iframe.js:

// Get URL parameter. 
function GetURLParameter(sParam) { 
    var sPageURL = window.location.search.substring(1); 
    var sURLVariables = sPageURL.split('&'); 
    for (var i = 0; i < sURLVariables.length; i++) { 
     var sParameterName = sURLVariables[i].split('='); 
     if ((sParameterName.length >= 2) && (sParameterName[0] === sParam)) { 
      return decodeURIComponent(sParameterName[1]); 
     } 
    } 
    return null; 
} 

document.getElementById("iframe").src = GetURLParameter("url"); 

Я также добавил "content/login/login_iframe.html" к "web_accessible_resources" в manifest.json. Но я получаю эти сообщения об ошибках в консоли:

login_iframe.js:14 Uncaught TypeError: Cannot set property 'src' of null 
rs=AItRSTPbuBGKt-Gq9QZ6xBfrjWRS7py0HA:13055 'webkitCancelRequestAnimationFrame' is vendor-specific. Please use the standard 'cancelAnimationFrame' instead. 
login_iframe.js:14 Uncaught TypeError: Cannot set property 'src' of null 

В чем проблема и почему document.getElementById("iframe") возвращение null и почему я получаю сообщение об ошибке дважды?

Я также попытался вставить login_iframe.js в качестве встроенного скрипта в login_iframe.html, но у меня появилось другое сообщение об ошибке, указывающее, что встроенный скрипт не разрешен.

ответ

2

Ваш HTML фрагмент:

<script src="login_iframe.js"></script> 
<iframe id="iframe"></iframe> 

Обратите внимание, что сценарий будет добавлен в DOM до #iframe элемента есть.

Выполняется синхронно, но document.getElementById("iframe") возвращает null - поскольку этот элемент еще не добавлен в DOM.

Теоретически, все, что вам нужно, чтобы избавиться от этой конкретной ошибки, - это переключить два тега вокруг.

Смежные вопросы