2015-10-15 417 views
1

我正試圖增強我們其中一個工具的GUI,但我失敗了。用戶界面由一個包含多個iFrame的主體組成,我想從中選擇一個並稍微改變內容。Tampermonkey在iframe中獲取表格?

問題是,當使用我的選擇器frame = $("iframe[src*='/vs/virt.jsp']");它看起來像它找不到該元素。

下面的代碼(沒有做任何事情比其他日誌):

// ==UserScript== 
// @name UI Tweaks 
// @version 0.2 
// @description Does stuff 
// @match https://*.local/vs/* 
// @run-at   document-end 
// @grant none 
// @require http://code.jquery.com/jquery-latest.js 
// ==/UserScript== 


console.log(window.location); 
console.log("before"); 
console.log($()); 
frame = $("iframe[src*='/vs/virt.jsp']"); 
console.log(frame.attr("id")); 
console.log("after"); 

當網頁上運行此我得到兩個頁面加載,它顯示的位置對象,之前和之後。但是框架對象完全是空的。

但是,在Chrome瀏覽器開發者控制檯中運行相同的事情後,頁面已加載我得到我正在尋找的元素。

我試過不同的方式來加載頁面加載後腳本等,但它仍然無法正常工作。

更新:

我說:

// @require  https://gist.github.com/raw/2625891/waitForKeyElements.js 

然後嘗試這樣:

waitForKeyElements (
    "iframe[src*='/vs/virt.jsp']", 
    test() 
); 

function test(){ 
    frame = $("iframe[src*='/vs/virt.jsp']"); 
    console.log(frame.attr("id")); 
} 

還是一樣的結果。值得注意的是我使用Tampermonkey,但也許它是一樣的?

編輯2:

function timer() { 
    frame = $("iframe[src*='/vs/virt.jsp']"); 
    console.log(frame.attr("id")); 
    setTimeout(timer, 1000); 
} 

timer(); 

它使輸出「不確定」,而如果我嘗試在Chrome開發者控制檯我得到的對象。這就像Tampermonkey無法訪問?

+1

'$(「iframe [iframe [src * ='/ vs/virt.jsp']」);'這是一個錯字,對,這不是實際的代碼? –

+0

這是一個錯字。現在糾正它。感謝您的觀察! – PatrikJ

+1

iframe元素可能稍後創建。嘗試使用'waitForKeyElements'或'MutationObserver'。 – wOxxOm

回答

2

由於您的iFrame與主頁位於同一個域,因此使用waitForKeyElements()來定位iframe更改相對簡單。它的設計考慮到了這種可能性。
傳遞一個有效的iFrame選擇器作爲第四個參數。

例如:

  1. 轉到this jsFiddle page。它動態地創建一個id tstIframe的iframe,它看起來像:

            Initial state

  2. 當你點擊按鈕將其添加文本的iframe的線 - 在同一個div comment

  3. 假設我們要處理的文本,那麼該腳本將這樣做:

    // ==UserScript== 
    // @name  Dynamic iframe content manipulator 
    // @match  http://fiddle.jshell.net/5zqfthx7/* 
    // @require  http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js 
    // @require  https://gist.github.com/raw/2625891/waitForKeyElements.js 
    // @grant  GM_addStyle 
    // ==/UserScript== 
    /*- The @grant directive is needed to work around a design change 
        introduced in GM 1.0. It restores the sandbox. 
    */ 
    waitForKeyElements (
        ".comment", 
        styleComment, 
        false, 
        "#tstIframe" 
    ); 
    
    function styleComment (jNode) { 
        jNode.css ("background", "lime"); 
    } 
    
  4. 當您安裝腳本,重新加載頁面,然後按下按鈕,你會看到每個新行得到有色,像這樣:

            Script in action


注:

  1. 不要在這種情況下@noframes。 Tampermonkey在這種iframe操作中沒有正確應用 - 尤其是iframe沒有src
  2. 當使用@require,始終使用@grant以外none,除非你知道究竟如何頁面的JS和腳本的互動會和衝突。
  3. Firefox上還提供了其他選項。 Chrome仍然有挑剔/有限的iframe支持。
  4. 最後,由於您的iFrame有一個src,,您通常可以將它編寫爲僅有的頁面。調整您的@match等,指令在iframe上觸發,也許將代碼包裝在if (self !== top) {... }結構中。例如,
    this answer