Use Javascript to get selected text in Mobile Safari

后端 未结 3 702
天命终不由人
天命终不由人 2021-02-07 20:16

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 a

3条回答
  •  不要未来只要你来
    2021-02-07 20:53

    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.

提交回复
热议问题