3

为Chrome扩展程序创建清单文件时,有一个选项all_frames,允许将内容脚本注入到顶部框架/ iframe中,或者全部注入。如何在Chrome扩展中控制(i)帧深度,即注入内容脚本?

我希望此行为在某些特定级别(例如2)停止。有没有办法指定它,最好是在清单上?或者至少在实际脚本中使用黑客?

的问题可以被翻译成:“是否有可能知道一帧有多深是一个HTML文档中

回答

4

您不能在清单中指定帧深度
但是,如果I帧有不同的URL?你可以(通过具有content_scripts阵列中的多个条目,在清单)运行针对他们不同的内容脚本

一个内容脚本可以通过编程确定与这样的代码的(I)帧的深度。

getFrameDepth (window.self); 

function getFrameDepth (winToID) { 
    if (winToID === window.top) { 
     return 0; 
    } 
    else if (winToID.parent === window.top) { 
     return 1; 
    } 

    return 1 + getFrameDepth (winToID.parent); 
} 



您可以针对this page at jsBin测试,如果您创建一个扩展如下:

manifest.json的:

{ 
    "manifest_version": 2, 
    "content_scripts": [ { 
     "all_frames":  true, 
     "js":    [ "iframe foo.js" ], 
     "matches":   [ "http://jsbin.com/enivux/*", 
           "http://jsbin.com/anomic/*", 
           "http://jsbin.com/ogaxoq/*", 
           "http://jsbin.com/ihegaq/*" 
          ] 
    } ], 
    "description":  "Detecting where an iframe is in the hierarchy", 
    "name":    "(i)frame Level identification", 
    "version":  " 1" 
} 


iframe的富。 js:

var frameDepth = getFrameDepth (window.self); 
var bodyColors = ["white", "pink", "lime", "cyan"] 

document.body.style.background = bodyColors[frameDepth]; 

function getFrameDepth (winToID) { 
    if (winToID === window.top) { 
     return 0; 
    } 
    else if (winToID.parent === window.top) { 
     return 1; 
    } 

    return 1 + getFrameDepth (winToID.parent); 
} 



注意,Chrome扩展将目前only run on iframes with a src attribute,只有当网址符合清单的匹配和水珠的要求。

+0

谢谢,我真的希望有一个解决方案的清单,但没关系! – zabetak

相关问题