Category Archives: JavaScript

[Weex]Error in creating project NPM: unable to load file D:\program files\nodejs\node_ global\ weex.ps1 Because scripts are not allowed to run on this system.

Use weex to create a new app and find NPM error:

npm : The file D:\Program Files\nodejs\node_global\weex.ps1 could not be loaded because running scripts is disabled on this system. For more information, see https:
/go.microsoft.com/fwlink/?LinkID=135170 in about_Execution_Policies.
Location Line:1 Character: 1
+ npm run dev
+ ~~~
    + CategoryInfo          : SecurityError: (:) [],PSSecurityException
    + FullyQualifiedErrorId : UnauthorizedAccess

Because it is forbidden to run scripts on this system, that is to say, you do not have permission

get-ExecutionPolicy
// Output: Restricted
// Restricted

Restricted means that the state is prohibited. Give permission:

Set-ExecutionPolicy -Scope CurrentUser

// At the prompt, enter.
RemoteSigned

Verify:

get-ExecutionPolicy
// Output: RemoteSigned

Then recreate the project.

How to introduce iconfont into uni-app

There are two ways to introduce iconfont into uniapp, one is introduced locally, the other is introduced online.

Let’s talk about the method of online introduction. Create your own project in iconfont, and then add some icons,

Select Unicode and copy the code. Then download the code to the local and find it in it iconfont.css We only use this one. After we get CSS, we put it into our uniapp project and post the code to replace the previous code

stay app.vue Introduce CSS file into

It’s easy to use

We can see that the above method is still introduced into the external chain. We generally don’t like it. We always feel that it’s not safe, so the local one is more appetizing

The iconfont file contains iconfont.ttf 、 iconfont.css , will iconfont.ttf File transpose Base64.
Recommended translation tool address: https://www.giftofspeed.com/base64-encoder/

Then open it iconfont.css File, modify the @ font face part, paste the converted Base64 code to the corresponding location, and set the code as follows:

@font-face { font-family: "iconfont";
 src: url(data:font/truetype;
charset=utf-8;
base64,Converted base64 content) format('truetype'); } .iconfont { display: inline-block; }

Finally, it is in the project App.vue Introduced in iconfont.css file

<style> @import "./font/iconfont.css"; </style>

How to use it in any component:

<view class="iconfont icon-XXX"></view>

How to open a page in a new window by Vue router

1. <router link>tag to open a new window:

The official document says that the V-link directive has been replaced by a new & lt; router link & gt; component directive, which has been completed by the component in Vue 2.

Note: <router link> does not support target = "_Blank ", if you want to open a new tab, you must use the <a> tab.

But in fact, vue2 version of <router link>supports target = “_The “blank” attribute (tag = “a”) is as follows:

1 <router-link target="_blank" :to="{path:'/home',params:{id:'8'}}">open home in a new page</router-link>

2. Programming navigation:

Sometimes it is necessary to realize page Jump in click event or function, so you can use the example method of router to realize it by writing code.

What we often use is$ router.push And$ router.go However, after vue2.0, this method does not support the properties of new window opening. This is the time to use this$ router.resolve , as follows

 1    goToLoanOrderDetail(loanOrderId, userId) {
 2       let routeData = this.$router.resolve({
 3         name: 'orderDetail',
 4         params: { loanOrderId, userId }
 5       });
 6       window.open(routeData.href, '_blank');
11     }

Just click the event to call this method

How to Block a frame with origin from accessing a cross origin frame

When the iframe is nested in different port numbers or even different IP addresses, an error is reported when the parent page calls the method of the child page

SecurityError: Blocked a frame with origin from accessing a cross-origin frame…

Cause of the problem

Under different port numbers, the traditional iframe nested method cannot be used.

document.getElementById("mainFrame").contentWindow.xxxx();

Cause

Homologous security policy
you can’t use JavaScript to access an <iframe>, if you can, it will be a huge security flaw. Prevent scripts from trying to access frames with different sources for the same source policy browser.

If at least one part of the address is not reserved, the source is considered different:

<protocol>://<hostname>:<port>/path/to/page.html

To access an iframe, the protocol, host name, and port must be the same as the domain.

Examples

Here’s what happens when you try to access the following URL

http://www.example.com/home/index.html

URL                                            RESULT 
http://www.example.com/home/other.html         -> Success 
http://www.example.com/dir/inner/another.php   -> Success 
http://www.example.com:80                      -> Success (default port for HTTP) 
http://www.example.com:2251                    -> Failure: different port 
http://data.example.com/dir/other.html         -> Failure: different hostname 
https://www.example.com/home/index.html.html   -> Failure: different protocol 
ftp://www.example.com:21                       -> Failure: different protocol & port 
https://google.com/search?q=james+bond         -> Failure: different hostname & protocol

How to Fix

Although the same origin policy prevents scripts from accessing the content of different origin sites, if you have both pages, you can use to window.postmessageand its related message events send messages between two pages to solve this problem.

On the main page:

var frame = document.getElementById('your-frame-id'); 
frame.contentWindow. postMessage (data, '*');

data can be string, boolean, number, array, object

In the iframe subpage
window. addEventListener ('message', function(event) { 
    //event.data gets the data passed to it
});

Note: the PostMessage of the parent page triggers the addeventlistener

After installing NPM, NRM LS reports an error throw new err_INVALID_ARG_TYPE(name, ‘string‘, value)

Error screenshot:

error screenshots are seen in the cli. Js file line 17 error,

According to the path to find the file:
open files found an error line 17, note down the original 17 rows instead as shown in figure:

//const NRMRC = path.join(process.env.HOME, '.nrmrc');(Note these codes)
const NRMRC = path.join(process.env[(process.platform == 'win32') ?'USERPROFILE' : 'HOME'], '.nrmrc');

After executing CMD, enter NRM ls problem solved

[ERR_INVALID_ARG_TYPE]: The “path“ argument must be of type string. Received undefined error

Start the React project and report the following error:

[ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received undefined
    at validateString (internal/validators.js:120:11)......

There are two possible reasons for this error. The solution is as follows:
The React – Scripts version may be too low. The solution is as follows:

   1. In package.json, replace "react-scripts": "^3.3.0" with
   "react-scripts": "^3.4.0"
   2. Delete the node_modules folder
   3. Run cnpm i for a second

2. Modify the config/webpackDevServer. Config. Js file, as follows:
Look at the config/webpackDevServer. Config. Js files have the following code:

       app.use(noopServiceWorkerMiddleware());

Modified into

app.use(noopServiceWorkerMiddleware('/'));

Done!

JS getting ${pageContext.request.contextPath} Get the root path of the project

As we know, direct access to the JSP EL expression in js is unable to obtain, if you want to get ${pageContext. Request. ContextPath} value, we can use the following two ways:
1, in the ${pageContext. Request. ContextPath} with single quotes, this is the most simple way
2. Create a form with type= “hidden”, for example:

<input name="rootUrl" id="rootUrl" type="hidden" value="${pageContext.request.contextPath}"/>

Then get the value of the form through the JS action:

//Get the project root path
var rootUrl = "";
$(function () {
    rootUrl = $("#rootUrl").val();
})

H5 page left and right stretch content area

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>resize</title>
</head>
<style>
  *,*:before,*:after{
    padding: 0;
    margin: 0;
    box-sizing: border-box;
  }
  body{
    display: flex;
    flex-direction: column;
    align-items: stretch;
    width: 100vw;
    height: 100vh;
    overflow: hidden;
  }
  header,footer{
    flex: none;
    width: 100%;
    height: 60px;
    background: lightgrey;
  }
  footer{
    position: relative;
    background: lightblue;
  }
  .main{
    flex: auto;
    display: flex;
    align-items: stretch;
  }
  .sidebar{
    flex: none;
    width: 200px;
    background: lightgoldenrodyellow;
  }
  .container{
    position: relative;
    flex: auto;
    background: #e0bfc4;
  }
  .resize{
    position: absolute;
    z-index: 100;
    touch-action: none;
  }
  .resize.horizontal{
    top: 0;
    bottom: 0;
    left: 0;
    width: 4px;
    cursor: e-resize;
  }
  .resize.vertical{
    left: 0;
    right: 0;
    top: 0;
    height: 4px;
    cursor: n-resize;
  }
</style>
<body>
  <header>Header</header>
  <section class="main">
    <acticle class="sidebar">Sidebar</acticle>
    <acticle class="container">Content
      <div class="resize horizontal" onmousedown="mousedown('horizontal')"></div>
    </acticle>
  </section>
  <footer>Bottom
    <div class="resize vertical" onmousedown="mousedown('vertical')"></div>
  </footer>
</body>
<script>

function mousedown(flag){
  document.onmousemove = function(){
    // console.log("flag",event,flag)
    if (flag === "horizontal"){
      if (event.x < 200 || event.x > 800) return
      var sidebar = document.querySelector(".sidebar")
      sidebar.style.width = event.x + "px"
    } else if(flag === "vertical"){
      if (event.y < 500 || event.y > 877) return
      var foot =  document.querySelector("footer")
      var top = Number(foot.getBoundingClientRect().top)
      var height = Number(foot.getBoundingClientRect().height)
      foot.style.height = height + top -event.y + "px"
    }
  }
}

document.onmouseup = function(){
  document.onmousemove = null
}

</script>
</html>

JS to determine whether the string contains a character

JS can use to determine whether a string contains another character
String method
1, the indexOf
IndexOf returns the position where the specified string was first found in that character. If it is not found, it returns -1
IndexOf takes two arguments. The first argument is the string to be searched and the second argument is the position to be retrieved

let str = 'abcde';
//For example, search from the third position of str 'a'
console.log(str.indexOf('a',2));// -1
console.log(str.indexOf('a'))// 0

2, lastIndexOf

LastIndexOf takes two arguments, the first is the string to be searched and the second is the position to be retrieved. The default is sting.length-1

let str = 'abcdea';
//For example, search from the third position of str 'a'
console.log(str.lastIndexOf('a',2));// 0
console.log(str.lastIndexOf('a'));// 5

3, includes
The includes() method determines whether a string contains the specified substring and returns true or false
Includes accepts two parameters, the first for the specified string and the second for the lookup location, which defaults to 0

let str = 'abcde';

console.log(str.includes('a'))//true
console.log(str.includes('a',1))//false

4, the match

g: Global search
: Ignoring case
I: The match method retrieving a specified value within a string, or finding a match of one or more regular expressions, returns null if not found (can also be used to query the number of occurrenches of a character in the string)

let str = 'abcdabcda';

console.log(str.match(/a/gi));//['a','a','a']
console.log(str.match(/z/gi));// null

5, the search
The seacrh method is used to retrieve the substring specified in the string, or to retrieve the substring that matches the regular expression, or to return -1 if none

let str = 'abcde';

console.log(str.search('a'));// 0

console.log(str.search(/A/i));//Use regular match to ignore case search Return 0

Regular expression RegExp objects
1. Test method
Retrieves the value specified in the string. Returns true or false.

let str = 'abcdef';

let reg = /A/i;
console.log(reg.test(str));// true

2. Exec method
Retrieves the value specified in the string. Returns the value found and determines its location.
Returns a matching value if there is one in the string, otherwise returns null.

let str = 'abcdef';

console.log(/a/.exec(str))// Return the matching object
console.log(/z/.exec(str))// null

Asynchronous loading method of Baidu map

The purpose of asynchronous loading is to improve the rendering performance of web pages in some scenarios.
Common synchronous loading code:

<!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>Document</title>
    <script type="text/javascript"
        src="https://api.map.baidu.com/api?v=1.0&type=webgl&ak=Your%20key"></script>
    <style>
        html,
        body,
        #map {
            width: 100%;
            height: 100%;
            margin: 0;
            padding: 0;
        }
    </style>
</head>
<body>
    <div id="map"></div>
    <script>
        var map = new BMapGL.Map('map');
        var point = new BMapGL.Point(116.404, 39.915);
        map.centerAndZoom(point, 10);
        map.enableScrollWheelZoom(true);
    </script>
</body>
</html>

Asynchronous loading method:
idea is to avoid initialization loaded directly, but put the initialization process in the init () function (), for other contents page finished loading, add script tags and callback function calls the init function

<!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>Document</title>
    <style>
        html,
        body,
        #map {
            width: 100%;
            height: 100%;
            margin: 0;
            padding: 0;
        }
    </style>
</head>
<body>
    <div id="map"></div>
    <script>
        function init(){
            var map = new BMapGL.Map('map');
            var point = new BMapGL.Point(116.404, 39.915);
            map.centerAndZoom(point, 10);
            map.enableScrollWheelZoom(true);
        }
        window.onload = function(){
            var script = document.createElement('script')
            script.src="https://api.map.baidu.com/api?v=1.0&type=webgl&ak=Your%20key&callback=init"
            document.head.appendChild(script)
        }
        
    </script>
</body>
</html>

CSS text more than 2 lines hidden and show ellipsis

Hide the text beyond two lines and show the ellipsis code as follows:

{
    overflow: hidden;
    text-overflow: ellipsis;
    word-break: break-word;
    display: -webkit-box;
    -webkit-line-clamp: 2; 
    -webkit-box-orient: vertical;
}

/* Autoprefixer: off */ If you find that two lines of text are displayed but no ellipsis is shown, add the following code:

/* autoprefixer: off */
{
    overflow: hidden;
    text-overflow: ellipsis;
    word-break: break-word;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
}