Extract src attribute from script tag and parse according to particular matches

前端 未结 1 478
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-02 09:46

So, I have to determine page type in a proprietary CRM, using JavaScript. The only way to determine the page type (that is, the only consistent difference on the front end)

1条回答
  •  迷失自我
    2021-01-02 10:18

    Well, you can start by collecting all of the script elements. With jQuery, that's as simple as

    var scripts = $("script");
    

    Then limit that set to the elements that have a src attribute:

    var scripts = $("script[src]");
    

    ...and further limit it to those with a src attribute beginning with "/modules/":

    var scripts = $("script[src^='/modules/']");
    

    ...which given your description should result in a set of exactly one element, from which you can now pull the src attribute value itself:

    var path = $("script[src^='/modules/']").attr('src');
    

    Ok, that was easy - now to extract the next part of the path. There are plenty of ways to do this, but split is quick & dumb: create an array of parts using '/' as the separator, then pick off the third element (which will be the one after "modules"):

    var pathPart = $("script[src^='/modules/']").attr('src').split('/')[2];
    

    Obviously, this is all very specific to the exact format of the script path you're using as an example, but it should give you a good idea of how to begin...

    0 讨论(0)
提交回复
热议问题