javascript - 使用 jquery 从文档头中删除脚本需要几秒钟,如何使其即时?
问题描述
我在 prod 中使用谷歌地图,为此我需要在我的文档头中添加一个脚本。该脚本包含google maps javascript api
我的应用程序正在使用的密钥。
已API key
加载服务器端,但如果有人执行检查元素,仍会出现。为了防止这种情况(ish),我正在从头中删除脚本jquery
。然而,这需要几秒钟,并且在它从 DOM 中消失之前查找 API 密钥非常容易。有没有办法强制它立即被移除,所以它只出现在头部的几分之一秒?
这是我正在使用的代码:
import Vue from 'vue'
let isApiSetup = false
let googleMapScript
Vue.prototype.$googleMaps = () => {
if (!isApiSetup) {
return new Promise((resolve, reject) => {
try {
isApiSetup = true
/* Resolve promise when google maps is loaded and remove script with API key from head */
window.googleMapsInit = () => {
delete window.googleMapsInit
// Remove script from head, but it takes a while
googleMapScript.remove()
resolve()
}
googleMapScript = document.createElement('SCRIPT')
googleMapScript.setAttribute(
'src',
`https://maps.googleapis.com/maps/api/js?key=${process.env.googleMapsAuthToken}&callback=googleMapsInit`
)
googleMapScript.setAttribute('async', '')
googleMapScript.setAttribute('defer', '')
document.head.appendChild(googleMapScript)
} catch (err) {
reject(err)
}
})
}
}
编辑:要清楚,我的钥匙已经受到限制。但显然这并不能防止欺骗,所以我希望加强整体安全性。
解决方案
请改用代理。
基本上,您在服务器上设置了一个端点,它将仅使用服务器上的密钥获取 googleMapScript,然后将获取的脚本提供给您的用户。在您的前端使用您的服务器端点src
作为<script>
. 这样,API 密钥永远不会提供给任何最终用户,它只包含在从您的服务器发送到 Google API 服务器的后端请求中。