如何使用 javascript 从 iframe 中获取选定的文本?
<html>
<body>
<script type="text/javascript">
function smth() {
if (document.getSelection) {
var str = document.getSelection();
if (window.RegExp) {
var regstr = unescape("%20%20%20%20%20");
var regexp = new RegExp(regstr, "g");
str = str.replace(regexp, "");
}
} else if (document.selection && document.selection.createRange) {
var range = document.selection.createRange();
var str = range.text;
}
alert(str);
}
</script>
<iframe id="my" width="300" height="225">
.....some html ....
</iframe>
<a href="#" onclick="smth();">AA</a>
</body>
</html>
使用 smth
函数,我可以从某些 div 中获取选定的文本,但它不适用于 iframe。 有什么想法如何从 iframe 获取选定的文本吗?
<html>
<body>
<script type="text/javascript">
function smth() {
if (document.getSelection) {
var str = document.getSelection();
if (window.RegExp) {
var regstr = unescape("%20%20%20%20%20");
var regexp = new RegExp(regstr, "g");
str = str.replace(regexp, "");
}
} else if (document.selection && document.selection.createRange) {
var range = document.selection.createRange();
var str = range.text;
}
alert(str);
}
</script>
<iframe id="my" width="300" height="225">
.....some html ....
</iframe>
<a href="#" onclick="smth();">AA</a>
</body>
</html>
with smth
function i can get selected text from some div, but it doesnt work with iframe.
any ideas how to get selected text from iframe ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
是放在外层文档上的。要在 iframe 中选择文档,您需要获取内部文档:
但请注意,WebKit 不支持
document.getSelection()
或document。选择。尝试用
window.getSelection()
替换它,它在 Firefox 和 WebKit 中都有效,但返回一个选择对象(范围周围的集合/包装器),它需要字符串:我不知道有什么意义其中:
RegExp
是基本的 JavaScript,可以追溯到最早的版本;它永远在那里,你不必去嗅它。多个空格的 URL 编码是完全没有必要的。您甚至不需要 RegExp 本身,字符串替换可以写为:Is on the outer document. To get the selection of the document in the iframe you need to grab the inner document:
Note however that WebKit does not support
document.getSelection()
ordocument.selection
. Try replacing it withwindow.getSelection()
which works in both Firefox and WebKit, but returns a selection object (a collection/wrapper around Ranges), which needs stringing:I'm not sure what the point of this is:
RegExp
is basic JavaScript dating back to the very earliest version; it will always be there, you don't have to sniff for it. The URL-encoding of multiple spaces is quite unnecessary. You don't even need RegExp as such, a string replace could be written as:您需要从 iframe 中的文档/窗口中获取选择。
You need to get the selection from the document/window in the iframe.
您无法访问来自与您所在域不同的域的
iframe
内的数据。这是由于同源政策。
You can't access data inside an
iframe
that is from a domain different than yours.This is due to the Same origin policy.
以下代码将返回选定的文本。
希望这对某人有帮助。
Following code will return the selected text.
Hope this will help to someone.
此代码适用于所有现代浏览器:
This code works in all modern browsers: