小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。
vue3防xss拦截
npm安装: npm install xss
挂载全局:
main.ts
import xss from "xss";
declare module "@vue/runtime-core" {
interface ComponentCustomProperties {
$xss: typeof xss;
}
}
const app = createApp(App);
app.config.globalProperties.$xss = xss;
vuex:
state: {
// xss攻击白名单
xssOptions: {
whiteList: {
span: ["class"],
p:["class"],
a: ["href", "title", "target"]
},
},
},
index.ts:
import { useProxy } from "@/utils";
const { proxy } = useProxy();
proxy.$xss(str, $store.state.xssOptions);==>使用:[变量名,数据]
utils:index.ts:
import { ComponentCustomProperties, getCurrentInstance } from "vue";
export function useProxy() {
const { proxy } = getCurrentInstance() as {
proxy: ComponentCustomProperties;
};
return {
proxy,
};
}
单页面引用:
index.ts:
// 高亮
const highLight = (content = "") => {
if (Data.keyword == "") return content;
if (content.indexOf(Data.keyword) == -1) return content;
if (content.indexOf(Data.keyword) != -1) {
// const itemArr = content.split(Data.keyword);
// console.log(itemArr);
var str = content.replaceAll(
Data.keyword,
`<span class="highlight">${Data.keyword}</span>`
);
return xss(str, $store.state.xssOptions);
}
};
按需引入:
xxx.vue
import xss from "xss";
/*
**Data.intro:要进行防xss注入的html
**$store.state['xssOptions']):vuex中的渲染白名单
*/
const getXssIntro = () => {
return xss(Data.intro || "无",$store.state['xssOptions']);
}
};