刚接触js,想通过写一个实际的chrome扩展来入门。想请教各位,js能获取到当前页面<a>中的url,那怎样才能获取url对应页面中的元素信息?

解决方案 »

  1.   

    天安门的地址是在北京,那你告诉我,天安门现在的旗杆下,有多少个保安?保安的手里拿的是什么?不可能直接取到的,是东是西,你得先看到那个东西再说。 先设置一个iframe, 将iframe的src指定为a中的url, 再取吧。
      

  2.   

    哦,所以是用js在html里加一个iframe,然后用css把它设成hidden(因为不想让用户看到),再用contentWindow()去取数据,是这样吗?
      

  3.   


    我已经生成了iframe,发现在这句出了问题,浏览器不工作了。(两个id都应该没问题)
    frameContent = document.getElementById("profileFrame").contentWindow.document.getElementById("header");
    请问是哪儿出了问题呢?
      

  4.   

    frameContent = document.getElementById("profileFrame").contentWindow.document.getElementById("header");已经验证了document.getElementById("profileFrame").nodeName = IFRAME,
    问题应该是出在contentWindow,不能用吗?
      

  5.   

    如果是chrome扩展的话我记得,Chrome扩展是可以随意Ajax数据而不会受到跨域的限制.
      

  6.   

    做一个测试, 建立两个页面: a.htm   ,   b.htm在三种浏览器中都是完全正常的。不过b.htm换成http://www.baidu.com就出错了,确实不能跨域。
    你再查查Chrome的开发代码吧,看有没有办法取得比较高的权限来做这个事情。1. a.htm<html>
    <head>
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js" type="text/javascript"></script>
        <script type="text/javascript">
            //IE8/IETest 6 , Firefox , Chrome 均可
            function test(){
                var iFrame = document.getElementById("profileFrame");
                var iFrameElement = iFrame.contentWindow.document.getElementById('content');
                alert(iFrameElement.innerHTML);
            }
            //IE8/IETest 6 , Firefox , Chrome 均可
            function testJQ(){
                var objHtml = $("#profileFrame").contents().find("#content").html();
                alert(objHtml);
            }
        </script>
    </head>
    <body>
        <div id="divM" style="width:100%;height:900px;" >
            <input type="button" onclick="test()" value="js获取子页面中的元素" /><br /><br />
            <input type="button" onclick="testJQ()" value="jQuery获取子页面中的元素" /><br /><br />
            <iframe id="profileFrame" src="b.htm" width="300" height="300" ></iframe>
        </div>
    </body>
    </html>
    2. b.htm
    <html>
    <head>
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    </head>
    <body>
        <div id="content" style="width:100%;height:900px;" >
            敢取我呀,不想死了?
        </div>
    </body>
    </html>
      

  7.   


    谢谢你的建议。查了chrome扩展的开发文档,扩展中写的js被孤立在一个环境中运行,只能操作matches中对应的页面,其它页面无法操作。昨天试出来另外一个办法,在iframe子页面把元素通过chrome.extension.sendMessage()发给background.html,background.html接到数据后再用chrome.tabs.sendMessage()发给父页面。