Chrome - 通过 frameId(不是 id 属性)查找 iframe

wai*_*uck 5 javascript iframe google-chrome-extension

我正在开发一个 chrome 扩展,它可以找到来自 iframe 的请求。现在我可以通过听chrome.webRequest来获取frameId,这样我就可以获得 frameId(请参阅链接中的 frameId 部分,而不是 iframe 标签中的 id 属性)。

我可以使用这个 frameId 来查找 iframe 吗?我想要的只是检索 iframe 标签的属性,如名称、宽度和高度。

谢谢

这是我基于Xan回答的工作代码。

//frameScript.js
(function() {

    var body = document.body,
        html = document.documentElement;

    var height = Math.max( body.scrollHeight, body.offsetHeight,
        html.clientHeight, html.scrollHeight, html.offsetHeight );
    var width = Math.max( body.scrollWidth, body.offsetWidth,
        html.clientHeight, html.scrollWidth, html.offsetWidth );

    return {
        width: width,
        height: height
    }
}());

//background.js
chrome.tabs.executeScript(currentTabId, {
                    allFrames: true,
                    file: 'frameScript.js'
                }, function(data) {
                    console.log(data);
                });
Run Code Online (Sandbox Code Playgroud)

Xan*_*Xan 1

您可以使用框架 ID 将内容脚本注入到确切的框架中(您需要主机权限,但您已经拥有用于 webRequest 的权限)。

从那里,您可以获得宽度和高度以及名称。碰巧的是,这些特定属性可以从框架本身内部访问 - 这不是获取元素<iframe>本身的通用解决方案。

chrome.tabs.executeScript(
  tabId,
  {frameId: frameId, file: "content.js"},
  function(data) { console.log(data[0]); }
);

// content.js

// Evaluate something to return it
{
  name: window.name,
  height: window.innerHeight
  width: window.innerWidth
};
Run Code Online (Sandbox Code Playgroud)