Chrome扩展程序:在注入给定页面后更改iframe源内容

时间:2014-09-01 07:08:39

标签: javascript iframe google-chrome-extension

我已经开始编写chrome扩展程序,我尝试做的是以下内容: 1)检测新标签负载,并在完全加载时执行(2) 2)将iframe注入加载的页面 3)更改iframe的src内部HTML。

我的清单是:(此刻我没有使用localhost权限)

{
    "manifest_version" : 2,
    "name" : "My extension",
    "version" : "0.1",
    "description" : "Extensioning",
    "background" : {
        "page" : "background.html"
        },

    "permissions": [
        "tabs","https://*/*","http://*/*","http://localhost/*"],
    "web_accessible_resources" : ["background.js","content_script.js","MainExtension.html","MainExtension.css","MainExtension.js","jquery-1.11.1.min.js"]
}

我的background.html:

<html>
    <head>
        <script type="text/javascript" src ="jquery-1.11.1.min.js"></script>
        <script type="text/javascript" src="background.js"></script>
    </head>
    <body>
    </body>
</html>

我的background.js(检测加载的标签并将脚本注入页面)

chrome.tabs.onUpdated.addListener(function(tabId,changeInfo,tab)
{
    if(changeInfo.status == "complete")
    {
        alert("good");
        chrome.tabs.executeScript(tabId,{ file : "content_script.js"});
    }

});

我的content_script.js :(添加元素&#39;注入框架&#39;与src&#34; MainExtension.html&#34;)

var f = document.createElement('iframe');
f.id = "injected_frame";
f.style.zIndex = "2147483647";
f.style.top = "10%";
f.style.left = "0px";
f.style.position = "fixed";
f.style.width = "320px";
f.style.height = "240px";
f.style.border = "0px";
f.style.margin = "0px";
f.style.padding  = "0px";
f.src = chrome.extension.getURL('MainExtension.html');
document.body.appendChild(f);

MainExtension.html(在iframe中显示):

<!DOCTYPE html>
<html>
<head >
    <link rel="stylesheet" href ="MainExtension.css">
    <script type="text/javascript" src ="jquery-1.11.1.min.js"></script>
    <script type="text/javascript" src ="MainExtension.js"></script>
</head>
<body>
<div id = "wrapper">
    <div id = "headersection">
        <p id = "imgwrapper">
            <img src ="mystock.png" alt = "My E" id = "logoimg">
        </p>
        <p id = "headertext">My Extension</p>
    </div>
    <hr>
    <div id = "infosection">
        <p> p found : bla1,bla2,</p>
        <p> a : s1 </p>
        <hr>
    </div>
</div>
<div id = "datas">sdfsdfsdfsdfsdf</div>
</body>
</html>

我想做的是: 在我在注入的脚本(content_script.js)中添加iframe之后,我想要更改MainExtention.html,它是&#39; inject_frame&#39;的src。元件。

我该怎么做?或者你能否提出其他选择?

感谢。

1 个答案:

答案 0 :(得分:0)

我会尝试以下两种方法之一:

1)直接从内容脚本向服务器发出数据请求(推荐)。

2)通过消息传递发送HTML:

修改content_script.js

chrome.runtime.onMessage.addListener(function(html) {
  if (html) {
    f.innerHTML = html;
  }
});

修改background.js以包含以下内容:

function onReceiveFromServer(html) {
  chrome.tabs.sendMessage(tabId, html);
}