“I’m participating in Excavation Creators Boot Camp # 4, click here to learn more!”
preface
It has been some time since I published my article last time. Recently, I have been a little lost in my work, and I am not interested in doing anything. I don’t know how to make a decision, probably due to the influence of the outside world and mentality.
Even if all kinds of reluctant, but today still want to raise interest to write an article, after all, signed up for the gold creation training camp, also listened to the big guy’s livestream explanation, so the mule is the horse to write out to walk, let everyone Chou Chou have got big guy’s essence. The old saying goes well: practice is the only standard to test truth, not to mention writing articles this matter is not a day to become, or to write more to be handy, so behind or to produce more quality articles to use its mutual encourage.
Today we are going to talk about how to make the project only support Google Chrome access view, other browsers when the access to block and ask to download Google Chrome?
Demand background
So background, why do we need to do this? The reason is that because of the company mermaid mixed, the computer knowledge is uneven, some white users in the clear advice to use Google browser on the premise of access, or download the shanzhai Google browser or use a lower version of the Internet Explorer browser for access, the final complaint of bugs in the program, can not be used normally; In this regard, in order to solve the customer service problems of the small white group and avoid wasting too much time on such problems, our leaders decided to “one size cuts”, that is, users who do not use Google Browser will be blocked and cannot enter the page to view, they need to download Google Browser to normally access the platform page.
From the above leads to the requirements we need to implement, that is, in the project to add the code to determine the browser and jump to the prompt page to download Google Chrome. The following is an example of what has been implemented:
thinking
I think when this demand is thrown out, some people must ask whether such a “one size fits all” is appropriate. Why not do compatibility? These problems certainly we have had to think, first of all about compatibility, now basic rarely use IE browser, users can’t say no can only say that very few, since the user groups rarely we don’t need perfect meet all browsers, as long as we do can satisfy 95% of users use of mainstream browsers without problems had enough; Compatibility will cost us a lot of time and may not be complete, so we choose to abandon the 5% of users, through other ways to tell them to choose the mainstream browser to save compatibility time, so that the cost performance is the best. Therefore, there is no compatibility for minority user groups, so there is a “one size fits all” approach; And then said that the “one size fits all” approach in the program development problem, in the program development we will certainly take into account all groups, do our best to make the user experience to the extreme, but due to the company’s current rules and the development environment, the development time is not enough to make us perfect, so we have this kind of treatment behavior.
Although justified, but as a code cleanliness of development, it is not a perfect solution, but it also can yet be regarded as a perfect solution, therefore, lies in how to understand the way, the question of whether or not properly is everything is in order to solve the problem and solve the problem, as to which way way there must be some reason to exist.
Back to the book, whether the above requirements are difficult, how difficult? What do you think? Take a look at the following:
- Where is the project judged? For what reason?
- What API does the browser use?
- How to encode and decode urls?
- How can the code make its own judgments?
The development of
All right, let’s finish the book. Now let’s solve that problem.
Problem a painted painted painted fostered fostered
To answer question 1, let’s talk about our platform: First of all, our main platform is to use Vue technology stack, some pages inside the main platform is belong to another using the React technology stack development platform (here called it platform 2, behind good understanding), that is, a platform page contains two kinds of technology development, but the main is the main platform to solve the problem of the joke, The main platform developed using the Vue technology stack, so the following descriptions may contain VUe-related terms.
Ok, the structure of the platform is understood, then say the solution.
We first consider to write the code for judging into the Created life cycle of the homepage to judge, but this will lead to the page entering the homepage of platform Settings first and then jumping to the reminder page, which is a little unfriendly experience; We then wanted to judge at the global guard beforeEach, but thought the code would be less elegant to handle there, so we didn’t do it. What other way is there to be elegant and solve the problem? That is the optimal solution we choose, which is to add logical code to the index. HTML page for judgment, and then redirect to the reminder page for reminder. The advantage of this is that after entering the page for url parsing, you can directly follow the judgment logic instead of entering other pages of the project, which makes the experience better.
How to do it? Here is the file directory and use of the screenshots, the follow-up questions will be solved one by one.
Question 2 u being fostered fostered fostered
According to the MDN front-end documentation:
Navigator: The interface represents the status and identity of the user agent. It allows scripts to query it and register themselves for some activities. You can retrieve navigator objects using read-only properties.Copy the code
The core method for JAVASCRIPT to determine the browser type is to use: navigator.userAgent, which returns the userAgent string of the current browser.
We can see some information about the browser in the Google Browser console by calling the relevant properties of the Navigator object, as shown below:
According to the introduction of MDN, the related properties of Navigator are shown in the following table:
attribute | describe |
---|---|
appCodeName | Returns the code name of the browser. |
appMinorVersion | Returns a secondary version of the browser. |
appName | Returns the name of the browser. |
appVersion | The platform and version information of the browser is displayed. |
browserLanguage | Returns the language of the current browser. |
cookieEnabled | Returns a Boolean value indicating whether cookies are enabled in the browser. |
cpuClass | Returns the CPU level of the browser system. |
onLine | Returns a Boolean value indicating whether the system is in offline mode. |
platform | Return to the operating system platform where the browser is running. |
systemLanguage | Returns the default language used by the OS. |
userAgent | Returns the value of the user-Agent header of the server sent by the client. |
userLanguage | Returns OS natural language Settings. |
From the table above, we can obtain the name, version information, CPU level and other information of the browser. If the requirements are not particularly strict and you need to make a judgment based on the browser, in fact, the navigator. UserAgent API is sufficient, as for other apis based on their own needs can be selected.
Painted painted painted three fostered fostered
Question three, why do WE encode urls first, and then how do we encode the rest?
In THE HTTP protocol, the transmission of parameter components is in the form of key=value. Multiple parameters need to be separated by ampersand. Servers such as http://www.xxx.com/index.html?name=zhangsan&age=18&sex=1, after receipt of the string, use the & symbol segmentation out of each parameter, and then use = to separate out the parameter values.
What happens when a user passes a parameter that contains a special character like ampersand or =? Such as http://www.xxx.com/index.html?name1=zhang&san=1, was meant to pass name1 = zhang&san = 1, but the server will be resolved as name1 = zhang and SAN = 1, the result is ambiguity.
So to solve the above problem, we need to encode the URL. Ok, so we know why, so how to encode and decode?
JS provides three function pairsurl
Encode and decode, respectivelyescape/unescape
.encodeURI/decodeURI
.encodeURIComponent/decodeURIComponent
.
The escape/unescape method:
The scape method returns a string value (in Unicode format) containing the contents of a CharString. All Spaces, punctuation, accents, and any other non-ASCII characters are replaced with the %xx encoding, where xx equals the hexadecimal number representing the character;
The unescape method returns the decoded String from the String encoded by the escape method.
Non-encodable characters: @ * / +
The encodeURI/decodeURI method:
The encodeURI method returns an encoded URL. If the encoding result is passed to the decodeURI, the original string is returned. EncodeURI does not encode the following characters: :, /, and; And “?” . Use encodeURIComponent to encode these characters.
The decodeURI method returns the decoded String from the String encoded with the encodeURI method.
Non-encodable characters:! # $& * () = : /; ? +
EncodeURIComponent/decodeURIComponent method:
The encodeURIComponent method returns an encoded URL. If you pass the encoding result to decodeURIComponent, the original string is returned. Because the encodeURIComponent method encodes all characters;
The decodeURIComponent method returns a decoded String from a String encoded with the encodeURIComponent method.
Non-encodable characters:! * ()
Note: To encode urls, the escape method is used for strings, not urls; EncodeURI and encodeURIComponent methods are used for Url encoding. In both cases, encodeURIComponent is recommended because of its larger coding range.
Question 4 u u being fostered fostered
How do I make my code run automatically? Then introduce self-executing functions: that is, self-executing functions execute the function itself inside the function.
How to understand? The following is an example:
function a() {
console.log('123');
}
a();
Copy the code
Define a function that calls a() if you want to execute it; A self-executing function is one that executes automatically when it is defined, without being called.
(function a() { console.log('123'); }) ();Copy the code
or
(function a() { console.log('123'); } ());Copy the code
Well, about the need to elicit thinking needs to use the solution and knowledge is about the introduction, so we take the knowledge to understand the implementation code posted behind it is much easier, please look down
The complete code
Create the browserCheck folder in the static folder and create the index.js, index.html, and redirect.js files in that folder.
Index. Js file:
Function () {let agent = navigator.userAgent; if (agent.indexOf('Chrome') === -1 || agent.indexOf('Edge') > -1) { location.href = '/static/browserCheck/index.html? originUrl=' + encodeURIComponent(location.href); }}) ();Copy the code
As can be seen from the code, we only checked for compatibility with Google Browser, including using navigator.userAgent to obtain browser information, encodeURIComponent to encode URL parameters, and using self-executing functions to execute functions automatically. This file is then imported into the project’s index.html file.
<script src="/static/browserCheck/index.js"></script>
Copy the code
Next is the index.html file, which displays the alert message and provides a Google Chrome download address:
<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, Initial - scale = 1.0 "> < title > (browser compatibility check) home page < / title > < script SRC ="/static/browserCheck redirect. Js "> < / script > < / head > < body > <style> * { margin: 0; padding: 0; } body { background: #EDF1F7; } .browser-check-box-wrap { margin: 300px auto 0 auto; width: 600px; height: 500px; } .browser-check-box-wrap h2 { font-size: 20px; text-align: center; } .browser-check-download-box { margin-top: 30px; text-align: center; } .browser-check-download-box h3 { font-size: 15px; text-align: center; } .browser-check-download-box p { margin-top: 20px; } .browser-check-download-box a { display: inline-block; width: 120px; height: 40px; line-height: 40px; color: #fff; background: #f60016; border: 1px solid #f60016; text-decoration: none; border-radius: 2px; } .browser-check-download-box a:hover { cursor: pointer; background-color: #FF696B; border-color: #FF696B; } </style> <div class="browser-check-box-wrap"> <h2> This site now only supports Google Chrome </h2> <div class="browser-check-download-box"> < H3 > Google Chrome Stable 64-bit edition </h3> <p> <img src="https://pc3.gtimg.com/softmgr/logo/48/21258_48_1450768968.png" alt="" /> </p> <p> <a Href = "https://dl.softmgr.qq.com/original/Browser/96.0.4664.45_chrome_installer-64.exe" > click download < / a > < / p > < / div > < / div > </body> </html>Copy the code
Redirect. Js file:
Function getQueryParams() {var params = {}; var href = location.href; if (href.indexOf('? ') === -1) { return params; } var search = href.split('? ').slice(-1)[0]; if (! search) { return params; } var temp = search.split('&'); temp.forEach(v => { if (! v) { return; } var index = v.indexOf('='); if (index > -1) { params[v.substring(0, index)] = decodeURIComponent(v.substring(index + 1)); }}); return params; } var agent = navigator.userAgent; console.log('agent', agent); if (agent.indexOf('Chrome') > -1 && agent.indexOf('Edge') === -1) { var url = '/'; var query = getQueryParams(); if (query && query.originUrl) { url = query.originUrl; } location.href = url; }}) ();Copy the code
As you can see, we define a function in the JS file to get the URL parameter, and then again determine the browser type, if it is Google Chrome, redirect directly to the source page to achieve the above product requirements.
The following graph shows the results of information on both Edge and IE11 browsers, and it becomes clearer why the agent. IndexOf (‘Chrome’) code is used to determine this because the Edge browser information contains Chrome characters.
At this point, how to make the project only support Google browser access to view the requirements of the implementation method is finished, the final implementation effect please see the background requirements of the last screenshot, the effect and experience is quite good. If you have such requirements, please refer to my implementation process, I hope it can help you dig friends ^_^
Past wonderful articles
- How to use Antd Table to create Echarts maps in React projects?
- How do I introduce and use external fonts in a front-end project?
- How to use the Amap plugin and wrap popover components in React projects?
- Data Visualization – How do I use the Echarts plug-in and encapsulate diagram components in React projects?
- How can I change the default DatePicker week selector in Antd?
- How to encapsulate the Vue watermark component and how to use it in React?
- The most powerful rich text editor? TinyMCE Series [3]
- The most powerful rich text editor? TinyMCE Series [2]
- The most powerful rich text editor? TinyMCE Series of articles [1]
- React project to implement a Checkbox style effect component
- 2022 First update: 3 Progress bar effects in front end projects
- Front-end Tech Trends 2022: You don’t come in and see how to earn it a small target?
- If ancient have programmers writing summaries, probably is such | 2021 year-end summary
- Front-end development specifications in front end team practice
- Javascript high-level constructors
- Javascript high-level inheritance
- Recursion and closure
After the language
Guys, if you find this article helpful, click 👍 or ➕. In addition, if there are questions or do not understand the part of this article, you are welcome to comment on the comment section, we discuss together.