2010-10-13 15 views
29

से कोई वेब पेज चल रहा है या नहीं, यह पता लगाने के लिए कि मैं जावास्क्रिप्ट के लिए नौसिखिया हूं। मैं कैसे पता लगा सकता हूं कि मेरी जावास्क्रिप्ट किसी वेब साइट (http: //) से स्थानीय फ़ाइल बना रही है या नहीं। यह करने के लिएकिसी वेबसाइट या स्थानीय फ़ाइल सिस्टम

उत्तर

57
switch(window.location.protocol) { 
    case 'http:': 
    case 'https:': 
    //remote file over http or https 
    break; 
    case 'file:': 
    //local file 
    break; 
    default: 
    //some other protocol 
} 
+2

एक 'https' जोड़े , और आप जाने के लिए अच्छा होगा। – Blackcoat

+1

यह सच नहीं है। स्थानीय रूप से एक वेब सर्वर पर होस्ट किए जाने पर साइट को स्थानीय रूप से होस्ट किया जा सकता है और अभी भी 'http' प्रोटोकॉल का उपयोग किया जा सकता है। – Nes

1

अन्य तरीके: मामले के रूप में अच्छी तरह से:

if (/^h/.test(document.location)) { 
    // remote file over http or https 
} else { 
    // local file 
} 

या

if (document.location.host) { 
    // remote file over http or https 
} else { 
    // local file 
} 

या (slow, अनुशंसित नहीं)

if ((''+document.location).indexOf('http') === 0) { 
// if (document.location.protocol.indexOf('http') === 0) { // another way 
    // remote file over http or https 
} else { 
    // local file 
} 
संबंधित मुद्दे