I am building a R Shiny app that sometimes will be seen standing alone and sometimes will be viewed in an iframe in another web page. I would like to have a different .css file depending on where it is viewed, so I need to add a JavaScript statement to pick the correct .css. What I have now is:
ui.r
headerPanel(winowTitle="PageTitle",
list(tags$head(
tags$script('type = "text/javascript", if(window.self === window.top) {
tags$link(rel="stylesheet", type="text/css", href="FullSite.css")}
else{ tags$link(rel="stylesheet", type="text/css", href="InFrame.css"})'),
(other stuff that works)), etc
When I run this the application works but it does not read either .css file. What am I doing wrong?
Thanks
Here is one way to do it. I have replaced the R code in script with javascript. The first line uses the ternary operator in javascript to set the value of the stylesheet to the appropriate one.
list(tags$head(tags$script('type = "text/javascript",
stylesheet = window.self === window.top ? "FullSite.css" : "InFrame.css"
$("head").append("<link rel=stylesheet type=text/css href=" + stylesheet + ">")
')))
UPDATE: Here is a better way to add the stylesheet dynamically. I have used this SO Post to modify my answer.
list(tags$head(tags$script('type = "text/javascript"', '
var ss = document.createElement("link");
ss.type = "text/css";
ss.rel = "stylesheet";
ss.href = window.self === window.top ? "FullSite.css" : "InFrame.css"
document.getElementsByTagName("head")[0].appendChild(ss);
')))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With