能否通过JavaScript为HTML页面添加头部?及Spring Boot环境下Frame页面X-Frame-Options报错的解决咨询
能否通过JavaScript为HTML页面添加头部?及Spring Boot环境下Frame页面X-Frame-Options报错的解决咨询
兄弟,先给你明确说:JavaScript没法给HTML页面添加HTTP响应头,包括你要设置的X-Frame-Options,原因很简单——这个响应头是服务器在把页面发送给浏览器的时候就已经带上了,JS是在浏览器端运行的代码,根本碰不到服务器发送响应的这个环节,所以你写的那段JS里的add_header完全没用,那是Nginx服务器配置里的指令,放在JS里浏览器根本不认识,只会报错或者直接忽略。
回到你的问题:你在Spring Boot环境下用<frame>标签时出现Refused to display...X-Frame-Options to 'deny'的错误,大概率是Spring Boot(尤其是如果集成了Spring Security的话)默认给所有响应加上了X-Frame-Options: DENY的头,这时候得在Spring Boot的服务器层面去修改这个头的设置,给你几个靠谱的解决办法:
方法一:全局统一设置响应头
创建一个全局的控制器通知类,让所有页面的响应都带上X-Frame-Options: SAMEORIGIN:
import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ModelAttribute; import javax.servlet.http.HttpServletResponse; @ControllerAdvice public class FrameHeaderConfig { @ModelAttribute public void setFrameHeader(HttpServletResponse response) { response.setHeader("X-Frame-Options", "SAMEORIGIN"); } }
方法二:给单个页面单独设置
如果只有特定页面需要这个头,就在对应的Controller方法里直接操作响应对象:
import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import javax.servlet.http.HttpServletResponse; @Controller public class YourPageController { @GetMapping("/your-frame-page") public String getFramePage(HttpServletResponse response) { // 给当前页面的响应添加头 response.setHeader("X-Frame-Options", "SAMEORIGIN"); return "your-page-view-name"; // 这里替换成你的页面视图名 } }
方法三:如果用了Spring Security
如果你的项目集成了Spring Security,它默认会强制设置X-Frame-Options: DENY,这时候得在Security配置里调整:
import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { super.configure(http); // 允许同源页面嵌套frame http.headers().frameOptions().sameOrigin(); } }
另外补充一句:你用JS生成frameset的代码本身是没问题的,只要服务器端把响应头设置对了,这个frameset就能正常加载内容,不用在JS里瞎折腾响应头的事~
备注:内容来源于stack exchange,提问作者Tim
相关产品推荐
相关产品推荐

