from ggplotly, open all new hyperlinks in the same new window/tab

Viewed 34

I am using the following example code where click on the point opens a link:

data(mtcars)
mtcars$urlD <- paste0("http://google.com/search?q=", gsub(" ", "+", rownames(mtcars)))

p <- ggplot(data=mtcars, aes(x=wt, y=mpg, color=factor(carb), customdata=urlD)) + geom_point() 
pp <- ggplotly(p)
ppp <- htmlwidgets::onRender(pp, "
     function(el, x) {
       el.on('plotly_click', function(d) {
         var url = d.points[0].customdata;
         window.open(url);
       });
     }
  ")

It works fine but every new click opens new window/tab. Is there any way to make it use the same window? (I mean not the window with the plot but the window where the first link was opened) In usual javascript, I would use the name parameter of window.open(), like this: window.open(url, 'MyTargetWindow'); - but it doesn't help here. Any workarounds?

1 Answers

You must be using Rstudio. window.open(url, 'MyTargetWindow') works in browser but not in Rstudio. If you click the "show in new window" button and open the plot in your browser, it works. The reason is window name is recognized in the same browser, but when you open a new browser (from Rstudio Viewer to the actual browser in this case), the name info is not passed. I am not aware of a solution to solve this cross-browser issue.

enter image description here

enter image description here

Related