Search code examples
coronasdk

Corona Labs - Open up links from newWebView in device's browser


I have written some of the content for my Corona app in HTML and I display it in my app using the native.newWebview. Within this HTML content, I have links to external web pages, for example https://google.com.

When a user clicks on the link in my app, I'd like my HTML content to remain in the app and for Google to open up in the device's web browser.

However, what happens is that when they click on a link in my app, Google will open up in both my app and in the web browser.

As a note, in iOS, it seems the first time the link is clicked, it opens up in just the device's default browser and not the app, but if you return to the app and click the link again it will open up in both the app and the browser. For Android it always opens up in both the app and in the browser.

Here is a simplified version of my code.

main.lua

local function webListener( event )
    if event.url then
        system.openURL(event.url)
    end
end

htmlContent = native.newWebView( display.contentCenterX, display.contentCenterY, display.contentWidth, display.contentHeight )
htmlContent:request( "links.html", system.ResourceDirectory )
htmlContent:addEventListener( "urlRequest", webListener )

And here is the html content with the link that is displayed in the app.

links.html

<html>
<head>
</head>
<body>
    Go to <a href="https://google.com/">Google</a>.
</body>
</html>

Solution

  • Try (tested)

    links.html

    <html>
      <head></head>
      <body>
        Go to <a href="#corona://https://google.com/>Google</a>.
      </body>
    </html>
    

    main.lua

    local function webListener( event )
        if event.url then
            local pattern = 'corona://'
            local position = string.find( event.url, pattern ) or 0
            local len = position == 0 and 0 or string.len( pattern ) 
            local url = string.sub( event.url, position + len )
            if len > 0 then -- ensures that the app doesn't try to open links.html in the default browser window
                system.openURL( url )
                --print( url )
            end
        end
    end
    
    local htmlContent = native.newWebView( display.contentCenterX, display.contentCenterY, display.contentWidth, display.contentHeight-2*100 )
    htmlContent:request( "links.html", system.ResourceDirectory )
    htmlContent:addEventListener( "urlRequest", webListener )