Remove referrer information from external links

This commit is contained in:
Zoey 2021-08-19 12:48:22 -07:00
parent c67fcd19a7
commit de4c97c74b

View file

@ -7,6 +7,7 @@ pub mod serving;
use std::{ use std::{
collections::HashMap, collections::HashMap,
path::{Path, PathBuf}, path::{Path, PathBuf},
str::FromStr,
}; };
use anyhow::Context; use anyhow::Context;
@ -16,6 +17,7 @@ use lol_html::{element, html_content::ContentType, HtmlRewriter, Settings};
use pulldown_cmark::{Options, Parser}; use pulldown_cmark::{Options, Parser};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use walkdir::WalkDir; use walkdir::WalkDir;
use warp::hyper::Uri;
const PAGES_PATH: &str = "pages"; const PAGES_PATH: &str = "pages";
const TEMPLATES_PATH: &str = "templates"; const TEMPLATES_PATH: &str = "templates";
@ -247,23 +249,37 @@ impl<'a> SiteBuilder<'a> {
let mut output = Vec::new(); let mut output = Vec::new();
let mut rewriter = HtmlRewriter::new( let mut rewriter = HtmlRewriter::new(
Settings { Settings {
element_content_handlers: vec![element!("head", |el| { element_content_handlers: vec![
el.prepend(r#"<meta charset="utf-8">"#, ContentType::Html); element!("head", |el| {
el.append(&format!("<title>{}</title>", title), ContentType::Html); el.prepend(r#"<meta charset="utf-8">"#, ContentType::Html);
if self.serving { el.append(&format!("<title>{}</title>", title), ContentType::Html);
el.append( if self.serving {
&format!(r#"<script src="/{}/_dev.js"></script>"#, STATIC_PATH), el.append(
ContentType::Html, &format!(r#"<script src="/{}/_dev.js"></script>"#, STATIC_PATH),
); ContentType::Html,
} else { );
el.append( } else {
&format!(r#"<base href="{}">"#, &self.site.config.base_url), el.append(
ContentType::Html, &format!(r#"<base href="{}">"#, &self.site.config.base_url),
); ContentType::Html,
} );
}
Ok(()) Ok(())
})], }),
element!("a", |el| {
if let Some(href) = el.get_attribute("href") {
if let Ok(uri) = Uri::from_str(&href) {
if uri.host().is_some() {
el.set_attribute("rel", "noopener noreferrer")?;
el.set_attribute("target", "_blank")?;
}
}
}
Ok(())
}),
],
..Default::default() ..Default::default()
}, },
|c: &[u8]| output.extend_from_slice(c), |c: &[u8]| output.extend_from_slice(c),