对百度页面进行文字选择,立即显示在我的页面中显示选中的文字

本文介绍了一种通过XMLHttpRequest跨域获取并显示iframe内选中文本的方法,适用于需要从子框架页面捕获文本并在父页面展示的应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<%@LANGUAGE="VBSCRIPT" CODEPAGE="936"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>无标题文档</title>
<script language="JavaScript">
document.onmouseup
=function()
{
   
if(document.selection.createRange().text!="")
    {
    window.parent.document.getElementById(
"txt1").value=document.selection.createRange().text;
    }

}

</script>
</head>

<body>
例如我的页面index.html中一个textfieid1
和一个iframe   src="www.baidu.com"   子框架
在子框架中打开了百度页面
然后选择一段文字 立即在文本框textfieid1 中显示你刚才选中的文字
这个问题难在 是在子框架页面中选取文字放到父页面的文本框中
</body>
</html>

回答:

要跨域訪問iframe中的內容,只有通過xmlhttp來獲取頁面的內容
HTML code

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
   
<title>未命名頁面</title>
   
   
<script type="text/javascript">
   
<!--
   
var xmlhttp;
   
   
function createHTTP()
    {
       
if (window.ActiveXObject)
        {
            xmlhttp
= new ActiveXObject("Microsoft.XMLHTTP");
        }
       
else if (window.XMLHttpRequest)
        {
            xmlhttp
= new XMLHttpRequest();
        }
    }
   
   
function GetData()
    {
        createHTTP();
        xmlhttp.onreadystatechange
= StateChange;
        xmlhttp.open(
"GET", "http://www.youkuaiyun.com", false);
        xmlhttp.send();
    }
   
   
function StateChange()
    {
       
if (xmlhttp.readystate == 4)
        {
           
if (xmlhttp.status == 200)
            {
                document.getElementById(
'frame1').contentWindow.document.body.innerHTML = xmlhttp.responseText;
                document.getElementById(
'frame1').contentWindow.document.onmouseup = ShowSelection;
            }
        }
    }
   
   
function ShowSelection()
    {
       
var selection = document.getElementById('frame1').contentWindow.document.selection;
        document.getElementById(
'txtShow').value = selection.createRange().text;
    }
   
   
//-->
    </script>
   
</head>
<body onload="GetData()">
   
<input type="text" id="txtShow" style="width:400px" />
   
<div>
       
<iframe width="100%" height="100%" id="frame1">
       
</iframe>
   
</div>
</body>
</html>

参考:http://topic.youkuaiyun.com/u/20080120/22/3ac9e744-2520-4a05-8306-24cee83f9bf1.html

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值