Use Javascript to get selected text in Mobile Safari

好久不见. 提交于 2019-12-03 16:29:39

问题


So I'm working on a bookmarklet where it would be ideal for me to grab the content selected by the user using the "loop". Both window.getSelection and document.getSelection are functions that I can call, however, they always return an empty string.

I believe the problem is that when you tap on the bookmark icon in Mobile Safari, the selection is released. For example, if you select some text, tap the "+", bookmark or other tab, the selection is unselected even if you cancel.

Any thoughts on if it is possible to get at this data at all? Or is this pretty much impossible?


回答1:


I think you would have to have the bookmarklet insert some content into the page that would operate on the selection. You might add a button to the top or bottom of the page, and when clicked it would act on the current selection. It could then clean up the added content or leave it there.




回答2:


The contents of the "loop" are not exposed to javascript in the mobile browser, period. So this is impossible (I am assuming that you are working in the full browser, not in the browser window created when you launch a "saved to home page" icon)




回答3:


I have a fairly simple idea.

var latestSelection = "";
while (true)
{
    var tmp;
    if ((tmp = document.getSelection()) != "")
        latestSelection = tmp;
}

This way you would always have the latest selection in the latestSelection variable. Of course it would be expensive to have a loop run like this all the time. So you will probably want to play around with listeners or at least timers.

Hope this helps.

Update: Don't use the above code as is.

Here is how you would write the same thing in objective-c:

- (void) updateSelection
{
    NSString * tmp = [webView stringByEvaluatingJavaScriptFromString:@"document.getSelection()"];
    if (![tmp isEqualToString:@""])
        latestSelection = tmp;
}

You could have a timer execute updateSelection every x time units. If you find some good notification that let's you know that the user has interacted with the webview, you could use that to update latestSelection.



来源:https://stackoverflow.com/questions/3137665/use-javascript-to-get-selected-text-in-mobile-safari

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!