简体   繁体   English

如何在前端javascript/浏览器中读取javascript文件

[英]How to read javascript file in frontend javascript/browser

Please read carefully before marking as dupe.在标记为欺骗之前,请仔细阅读。

I want to read a javascript file on frontend.我想在前端读取一个javascript文件。 The javascript file is obviously being used as a script on the webpage. javascript文件显然被用作网页上的脚本。 I want to read that javascript file as text, and verify if correct version of it is being loaded in the browser.我想以文本形式读取 javascript 文件,并验证浏览器中是否加载了正确的版本。 From different chunks of text in the js file, I can identify what version is actually being used in the end user's browser.从 js 文件中的不同文本块,我可以确定最终用户浏览器中实际使用的版本。 The js file is main.js which is generated by angular build. js文件是main.js build生成的main.js。

I know we can do something like creating a global variable for version or some mature version management.我知道我们可以做一些事情,比如为版本或一些成熟的版本管理创建一个全局变量。 But currently, on production site, that will mean a new release, which is couple of months from now.但目前,在生产现场,这将意味着几个月后的新版本。 Only option I have right now is html/js page, which can be directly served from production site, without waiting for new release.我现在唯一的选择是 html/js 页面,它可以直接从生产站点提供,无需等待新版本。

So my question is, is it possible we can read a javascript file as text in hmtl/js code in the browser.所以我的问题是,我们是否可以在浏览器中以 hmtl/js 代码读取 javascript 文件作为文本。

an idea can be:一个想法可以是:

  1. use fetch api to get a container that can be use to async load the script https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API使用fetch api 获取可用于异步加载脚本的容器 https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API

  2. use text() method which return a promise to get text content使用返回 promise 的text()方法获取文本内容

    fetch('http://localhost:8100/scripts.js').then((res) => res.text()).then(scriptContent => { // scriptContent contain the content of your script // if (scriptContent.includes('version: 1.1.1') console.log(scriptContent); });

this is absolutely not an efficient way, but since you want to work without any new version release or working with a version management system这绝对不是一种有效的方法,但是因为您想在没有任何新版本发布或使用版本管理系统的情况下工作

here is the thing assume file's checksum (md5 sha125 or anything) of V1.0 equals X and you will calculate before the coding part.这是假设 V1.0 的文件校验和(md5 sha125 或任何东西)等于 X,您将在编码部分之前进行计算。

if checksum(X) != X{
location.reload() 
}

would help for a security features too since it's an important project.也将有助于安全功能,因为它是一个重要的项目。

another way of controlling this situation is changing the main.js file's name if it is possible.控制这种情况的另一种方法是在可能的情况下更改 main.js 文件的名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM