Javascript Gmail上的JS文本选择
我正在构建一个bookmarklet,它接收所选文本并将其发送回我的服务器进行处理。除了Gmail,它在所有网站上都能正常工作。任何人都知道如何让它在Gmail上工作。以下是我正在使用的代码:Javascript Gmail上的JS文本选择,javascript,gmail,bookmarklet,Javascript,Gmail,Bookmarklet,我正在构建一个bookmarklet,它接收所选文本并将其发送回我的服务器进行处理。除了Gmail,它在所有网站上都能正常工作。任何人都知道如何让它在Gmail上工作。以下是我正在使用的代码: var selectedText = ''; if (window.getSelection) { selectedText = window.getSelection(); } else if (document.getSelection) { selectedText = document.g
var selectedText = '';
if (window.getSelection) {
selectedText = window.getSelection();
} else if (document.getSelection) {
selectedText = document.getSelection();
} else if (document.selection) {
selectedText = document.selection.createRange().text;
} else {
selectedText = document.activeElement.contentWindow.getSelection();
};
最后一个案例在Firefox的Gmail中对我来说很好。但该代码存在一些缺陷:
返回一个window.getSelection()
对象,而不是字符串(我到处都能看到,我想这是PPK的错)。您需要Selection
selectedText=”“+window.getSelection()代码>
- 最后一个案例包括非IE浏览器中的iFrame,但不包括IE;我认为(但不确定)IE中的
可以指向iframedocument.activeElement
var selectedText = '';
if (window.getSelection) {
selectedText = "" + window.getSelection();
} else if (document.getSelection) {
selectedText = document.getSelection();
} else if (document.selection) {
selectedText = document.selection.createRange().text;
} else if (document.activeElement.contentWindow) {
var win = document.activeElement.contentWindow;
if (win.getSelection) {
selectedText = win.getSelection();
} else if (win.document.selection) {
selectedText = win.document.selection.createRange().text;
}
};
我碰到了同样的问题,发现你的问题我自己也在寻找答案 据我所知,代码中的问题不是window.getSelection在gmail中没有定义,而是getSelection().toString()返回一个零长度字符串,尽管文本被选中。在Firefox中,Tim Down的解决方案对我有效,但在Chrome中不起作用,因为contentWindow中不可用 下面我修改过的代码可以在页面上的任何框架中进行迭代,它在Gmail中为我在Firefox、Chrome和Safari中工作。(我没有在其他浏览器中测试过)
var selectedText='';
if(window.getSelection){
selectedText=window.getSelection().toString();
}
如果(selectedText==''){
var frames=window.frames;
对于(var i=0;i
这对我在gmail中使用firefox 3.6很有效,Firefox的chrome浏览器中browser.js文件中的函数getBrowserSelection()用于上下文菜单搜索
var focusedWindow = document.commandDispatcher.focusedWindow;
var selection = focusedWindow.getSelection();
谢谢你的帮助,提姆,但这对我来说在Gmail中不起作用。@conorwade:需要更多的细节,比如浏览器,你在Gmail中的哪个视图以及选择的位置。很好的解决方案。正如您在编程中所演示的,您不能依赖父窗口中的文本选择。我发现,如果谁投了反对票,而没有说明原因,那就太糟糕了。好问题,康纳,祝你好运。Goshido听起来像是一次惊人的冒险。这也适用于框架内的选定文本。
var focusedWindow = document.commandDispatcher.focusedWindow;
var selection = focusedWindow.getSelection();