2012-12-02 75 views
1

我想通過Chrome擴展編輯iframe的內容,但無法通過iframe的contentWindow/contentDocument返回未定義的內容。 四處尋找答案,正如我已經理解它,如果iframe從一開始就存在於頁面中,它很容易修復,但事實並非如此。 有問題的iframe是gmail撰寫的文本區域,它以iframe的形式出現,並且它被動態添加到DOM中。 有沒有辦法通過chrome擴展來做到這一點?從Chrome擴展訪問/編輯iframe的內容

編輯: 對不起。 Rob W讓我意識到contentDocument確實可以被訪問。我在這裏要做的是在Gmail中添加一些額外的功能,在工具欄中有一個按鈕,在撰寫窗口中添加一些html。我現在有按鈕部分的工作,它增加了HTML,但它不會在應該,因爲我不能爲了做這個訪問contentWindow像其插入符做到這一點:

range = iWindow.getSelection().getRangeAt(0); 
node = range.createContextualFragment(html); 
range.insertNode(node); 

任何解決這個?

回答

2

contentWindow is not accessible in Chrome extensions。另一方面,
contentDocument正確地返回框架內的文檔,前提是iframe處於相同的原始位置,對於Gmail來說就是如此。

下面是Gmail的示例。爲了簡單起見,我假定文檔中只有一個編輯器。

var poller = setInterval(function() { 
    var editor = document.querySelector('iframe.editable'); 
    if (editor && editor.contentDocument && !editor.__rwHandled) { 
     editor.__rwHandled = true; // Run once for an editor instance 
     var textNode = document.createTextNode('It works!'); 
     editor.contentDocument.body.appendChild(textNode); 
    } 
}, 200); 

每當你想停止輪詢,只需使用clearInterval(poller);。確保您檢測的方法便宜。例如:查詢DOM節點是好的,打開新窗口不是。

+0

感謝您的回答。我已經編輯了我的問題。我很抱歉,我確信這是因爲我沒有足夠的經驗,但我並沒有真正理解你的答案。我做了很多嘗試,並且嘗試使用executeScript在iframe中添加contentscript,但我確實無法完成它。對不起,我很欣賞迄今爲止的幫助。 – Clox

+0

@Clox這是因爲你的代碼真的需要訪問窗口對象,因爲使用'window.getSelection();'。 [注入腳本](http://stackoverflow.com/questions/9515704/building-a-chrome-extension-inject-code-in-a-page-using-a-content-script/9517879#9517879)哪你想要什麼。如果您想在頁面和內容腳本之間進行通信,請設置一個自定義事件或[使用'postMessage'](http://stackoverflow.com/a/13271692/938089?accessing-iframe-from-chrome-extension) 。 –

+1

它似乎在Gmail中的iframe不總是從同一個來源加載;如果您在主電子郵件列表視圖中將鼠標懸停在發件人上,您會看到一個小框(他們顯然稱爲懸浮卡)。此框由來自以下位置的iframe加載創建:https://apis.google.com/u/0/_/streamwidgets/hovercard?origin = https%3A%2F%2Fmail.google.com ... - 您可以影響這些iframes「all_frames」:真正的http://stackoverflow.com/questions/6641729/in-chrome-extension-content-scripts-cant-affect-inside-the-if​​rame?rq=1 –