Not allowed to load local resource ошибка

Okay folks, I completely understand the security reasons behind this error message, but sometimes, we do need a workaround… and here’s mine. It uses ASP.Net (rather than JavaScript, which this question was based on) but it’ll hopefully be useful to someone.

Our in-house app has a webpage where users can create a list of shortcuts to useful files spread throughout our network. When they click on one of these shortcuts, we want to open these files… but of course, Chrome’s error prevents this.

enter image description here

This webpage uses AngularJS 1.x to list the various shortcuts.

Originally, my webpage was attempting to directly create an <a href..> element pointing at the files, but this produced the «Not allowed to load local resource» error when a user clicked on one of these links.

<div ng-repeat='sc in listOfShortcuts' id="{{sc.ShtCut_ID}}" class="cssOneShortcutRecord" >
    <div class="cssShortcutIcon">
        <img ng-src="{{ GetIconName(sc.ShtCut_PathFilename); }}">
    </div>
    <div class="cssShortcutName">
        <a ng-href="{{ sc.ShtCut_PathFilename }}" ng-attr-title="{{sc.ShtCut_Tooltip}}" target="_blank" >{{ sc.ShtCut_Name }}</a>
    </div>
</div>

The solution was to replace those <a href..> elements with this code, to call a function in my Angular controller…

<div ng-click="OpenAnExternalFile(sc.ShtCut_PathFilename);" >
    {{ sc.ShtCut_Name }}
</div>

The function itself is very simple…

$scope.OpenAnExternalFile = function (filename) {
    //
    //  Open an external file (i.e. a file which ISN'T in our IIS folder)
    //  To do this, we get an ASP.Net Handler to manually load the file, 
    //  then return it's contents in a Response.
    //
    var URL = '/Handlers/DownloadExternalFile.ashx?filename=' + encodeURIComponent(filename);
    window.open(URL);
}

And in my ASP.Net project, I added a Handler file called DownloadExternalFile.aspx which contained this code:

namespace MikesProject.Handlers
{
    /// <summary>
    /// Summary description for DownloadExternalFile
    /// </summary>
    public class DownloadExternalFile : IHttpHandler
    {
        //  We can't directly open a network file using Javascript, eg
        //      window.open("\SomeNetworkPathExcelFileMikesExcelFile.xls");
        //
        //  Instead, we need to get Javascript to call this groovy helper class which loads such a file, then sends it to the stream.  
        //      window.open("/Handlers/DownloadExternalFile.ashx?filename=//SomeNetworkPath/ExcelFile/MikesExcelFile.xls");
        //
        public void ProcessRequest(HttpContext context)
        {
            string pathAndFilename = context.Request["filename"];               //  eg  "\SomeNetworkPathExcelFileMikesExcelFile.xls"
            string filename = System.IO.Path.GetFileName(pathAndFilename);      //  eg  "MikesExcelFile.xls"

            context.Response.ClearContent();

            WebClient webClient = new WebClient();
            using (Stream stream = webClient.OpenRead(pathAndFilename))
            {
                // Process image...
                byte[] data1 = new byte[stream.Length];
                stream.Read(data1, 0, data1.Length);

                context.Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", filename));
                context.Response.BinaryWrite(data1);

                context.Response.Flush();
                context.Response.SuppressContent = true;
                context.ApplicationInstance.CompleteRequest();
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

And that’s it.

Now, when a user clicks on one of my Shortcut links, it calls the OpenAnExternalFile function, which opens this .ashx file, passing it the path+filename of the file we want to open.

This Handler code loads the file, then passes it’s contents back in the HTTP response.

And, job done, the webpage opens the external file.

Phew ! Again — there is a reason why Chrome throws this «Not allowed to load local resources» exception, so tread carefully with this… but I’m posting this code just to demonstrate that this is a fairly simple way around this limitation.

Just one last comment: the original question wanted to open the file «C:02.jpg«. You can’t do this. Your website will sit on one server (with it’s own C: drive) and has no direct access to your user’s own C: drive. So the best you can do is use code like mine to access files somewhere on a network drive.

While inspecting a webpage in your browser’s Console, you might have come across the error message “Not Allowed to Load Local Resource.” This error message pops up when you try to load local resources in your browser, be it an image, scripts, or CSS file.

However, other web page elements may load normally, but a specific file will create the problem. For instance, you may face some of these error messages: net::ERR_CONNECTION_REFUSED, net::err_name_not_resolved, or the server responded with a status of 404.

Whatever the instances may be, we will guide you through the fixes that will help you sort out this error easily.

Before moving to the fixes section, let’s point out some causes why you see the Not Allowed to Load Local Resource Error:

  • Files blocked by Chrome security
  • Disabled local file access
  • Problems with DNS server
  • Outdated Host cache

How to Fix Not Allowed to Load Local Resource Error

Fixing this error is not that tedious and time consuming. Making minor changes in your browser and terminal will help you resolve this error.

I have compiled a list of 5 fixes that you can apply when you face the error. Let’s dive straight into them:

Try Disabling the Chrome Security Settings

Since the error is caused due to the security feature of Chrome, the first thing you can do is disable the security settings. It is not recommended, but if it solves the issue, you can proceed with it.

Make sure the resource you are trying to load is not malicious. You should take care of it yourself. Else you will be vulnerable to attacks. Consider re-enabling the security after you are done loading the resources. Here’s how to do it:

  1. Click the menu button () in the top right corner of the Chrome window.
  2. Select Settings from the list of options.
  3. Click Privacy and Security from the left pane of the Settings page.
  4. Select the Security menu in the right section.
  5. Under Safe Browsing, click No protection (not recommended).
    no protection
  6. In the next popup, click the Turn off button.
    turn off safe browsing

Change DNS Settings

Domain Name System (DNS) functions as a mediator between you and a web server for name resolution. It translates the domain names into IP addresses to load resources from the web server. 

Your computer obtains a DNS address dynamically from your ISP. Sometimes, it may stop working, and your Internet connection may go down. You also face the titled error when there is an issue in the DNS server. 

Moreover, if you are using a DNS address other than provided by your ISP, Chrome may block it, raising security concerns. You can use the Google DNS servers and see if it fixes the problem. Follow these steps:

  1. Right-click the Start button and select Run from the list of options.
  2. Type ncpa.cpl in the text field and hit Enter to open Network Connections.
  3. Right-click the active network adapter and click Properties.
  4. Select the Internet Protocol Version 4 (TCP/IPv4) option under the Networking tab.
  5. Click the Properties button.
    properties-of-tcp-ipv4
  6. In the new Properties window, click Use the following DNS server addresses and enter the following IP address.
    • Preferred DNS server: 8.8.8.8
    • Alternate DNS server: 8.8.4.4
      preferred-and-alternate-dns-servers
  7. Check Validate settings upon exit option and Click OK to save the changes.

Clear Host Cache

Chrome has a built-in DNS cache server to help improve the website loading speed. As we already discussed, DNS maps domain name to IP address; when the IP address for a website is changed, the cache may load the older IP address and cause the issue. It can even decrease the website loading speed.

In such a scenario, you must clear the host cache and see if the issue is solved. Here’s how to clear it:

  1. Copy and paste chrome://net-internals/#dns in the address bar of Chrome.
  2. Click the Clear host cache button.
    clear host cache
  3. Exit from the browser and relaunch it to see if the issue persists.

Set Up an HTTP Server

If you face the Not Allowed to Load Local Resource error on Chrome, it is mostly due to security reasons. What you can do is set up an HTTP server on your computer and start to serve the files locally. While doing so, files will not be fetched from the network, and Chrome will stop blocking them. Here’s how you can do it:

  1. Launch your terminal.
  2. Type npm install -g HTTP-server and hit Enter.
  3. Go to the root folder and open it. In this case, the root folder is where you want to store your files. Type HTTP-server ./
  4. You will see something like  http://localhost:8080 on the output screen of your terminal. You can retrieve everything stored here. For example, an image file named deepen.png can be retrieved using background: url('https://localhost:8080/deepen.png');

Install HTTP Server Extension For Chrome

You can also easily set up an HTTP server using the Chrome extension, namely Web Server for Chrome. It is the extension that runs offline and helps serve files and webpages to network from a local folder. It would fix issues if you had any while setting up an HTTP server manually. Follow these steps to install the extension:

  1. Go to the Web Server for Chrome extension page.
  2. Click the Add to Chrome button. You may be prompted to sign in to Chrome to add the extension.
  3. Once installed, open the extension.
  4. Click the CHOOSE FOLDER button and browse your project folder.
    choose folder
  5. Then click the address shown under Web server URL and run the web server.
    web server url

Related Questions

What Are the Programs Affected By “Not allowed to load local resource”?

Chromium-based programs are mostly the victims of Not allowed to load local resource error. Because of having a strong security mechanism, they prevent you from loading files from local machines to protect you from any kind of malicious attacks.

They instead require you to load resources from a web server. Some Chromium programs are Google Chrome, Microsoft Edge, Opera, NodeJS, Atom, and Electron.

How Do I Enable Local Access in Chrome?

By default, If you have not given local access to Chrome, it cannot load the files from your local machine. In such a case, you may be facing the titled error with 404 status code. Follow these steps to enable local access:

  1. Close and Exit Chrome.
  2. Hit Windows + R key on your keyboard to open the Run dialog box.
  3. Type chrome.exe --allow-file-access-from-file in the text field and hit Enter.

What is the Difference Between 403, 404, and Not Allowed to Load Local Resource Error?

403 is a resource forbidden error. It occurs when you try to access the webpage or any resource you are not allowed to. You may not have enough permissions, and you might face an error.

You normally see the 404 error as Error 404 Page Not Found! It states that a webpage you want to view does not exist. It doesn’t mean the Server is down. It means the Server is reachable but cannot find the page you are looking for.

While, as discussed entirely in this post, Not Allowed to Load Local Resource error arises with the modern Chromium programs. Since they are equipped with high security of V8 engines, they don’t allow loading the local resources, and you may face the issue.

Not allowed to load local resource: <тут путь к файлу> . Пытаюсь сделать аватарку пользователя через

<img src="<путь к директории/<?php echo $profile['avatar'];?>>"

Но ловлю ошибку. Путь к файлу правильный, сам файл существует. Видел проблему в интернете в браузере chrome, но я использовал для теста Yandex. (P.S. Все инструкции,которые я находил, написаны на английском и я не могу понять чёткую инструкцию, что делать. Просьба не кидать ссылки, а написать, что сделать, если это возможно).
Есть идеи, как это исправить?

Your network settings might cause this error in Chrome

by Afam Onyimadu

Afam is a geek and the go-to among his peers for computer solutions. He has a wealth of experience with Windows operating systems, dating back to his introduction… read more


Updated on July 19, 2022

Fact checked by
Alex Serban

Alex Serban

After moving away from the corporate work-style, Alex has found rewards in a lifestyle of constant analysis, team coordination and pestering his colleagues. Holding an MCSA Windows Server… read more

  • You may be restricted from accessing resources when attempting to read XML or JSON data saved in a local file during project testing or creation.
  • This error code is more common on Javascript files, React, as well as file downloads and HTML images.
  • Stored data on your Host DNS cache could mean that you try to access resources to old IPs and hence will not be successful. 

chrome not allowed to load local resource

Instead of fixing issues with Chrome, you can try a better browser: OperaYou deserve a better browser ! 350 million people use Opera daily, a fully-fledged navigation experience that comes with various built-in packages, enhanced resource consumption and great design. Here’s what Opera can do:

  • Easy migration: use the Opera assistant to transfer exiting data, such as bookmarks, passwords, etc.
  • Optimize resource usage: your RAM memory is used more efficiently than Chrome does
  • Enhanced privacy: free and unlimited VPN integrated
  • No ads: built-in Ad Blocker speeds up loading of pages and protects against data-mining
  • Download Opera

This article will explore what to do when you get the error – Chrome not allowed to load local resource.

In the early 2010s, the Chrome browser supplanted earlier browsers such as Mozilla Firefox and Internet Explorer as the industry standard, and it currently dominates online browsers.

Google Chrome is quick, simple to use, and has the most extensive addon library of any browser. It is an excellent browser for both business and personal use.

This error is similar to the HTTPS errors in Google Chrome. So let’s get to it.

What does not loading local resources mean?

When you get this error, it restricts you from viewing specific websites, web resources, or files.

It is common in some modern browsers where Javascript is disabled by default. Browsers like Chrome may disable this setting because it is associated with malicious attacks.

In other cases, bad network configurations may restrict your access to specific resources, and in such cases, you may have to tweak your network settings.

Whatever the case, you must note that tech also comes with flaws, and you may have to reset your browser or update it to solve the problem.

Other similar problems users have encountered include:

  • Chrome not syncing – When Chrome does not sync, you can no longer share similar data across devices.
  • Google Chrome not shutting down correctly – This is an error where the browser would no longer shut down when you use the close button.
  • Chrome ERR_FILE_NOT_FOUND error – This error is associated with opening new pages or tabs and is often caused by malfunctioning plugins.
  • Google Chrome is running slow – This issue means your browser is lagging. It might also be a general PC problem.

This error is not unique to Chrome. Edge not allowed to load local resources is also a common complaint. Regardless of the browser, this error has been noticed mainly among users using React, Javascript files, WordPress, as well as in HTML images, and file downloads.

Is your current browser using too many PC resources? It’s time for an upgrade

Opera GX is the first gaming browser that allows custom control over resources. It lets you set a custom limit for how much RAM and CPU each tab can use.

You can also limit bandwidth usage and benefit from online privacy with a free, unlimited VPN. Enabling battery mode, dark mode and the adblocker can also help load pages faster.

Opera GX

Opera GX

Surf the web error-free with this lightweight browser with customizable performance features!

How do I fix not allowed to load local resource?

1. Change to Public DNS

  1. Right-click on the Start menu and click on Settings.
  2. On the left pane, click on Network & Internet, then scroll down and select Advanced network settings on the right pane.
  3. In the Related settings section, click on More network adapter options.
    chrome not allowed to load local resource
  4. Right-click on your adapter and select Properties.
  5. Select Internet Protocol Version 4 (TCP/IPv4), then click the Properties button.
  6. Under the section for Preferred DNS server, type 8.8.8.8, and for the Alternate DNS server section, type 8.8.4.4, tick Validate settings upon exit and hit OK.
    chrome not allowed to load local resource
  7. Relaunch your browser and try re-accessing the resource.

Updating your network setting’s DNS servers is a simple solution to this problem. For example, you may use any publicly accessible DNS servers on the internet. Lastly, consistently utilize recognized and trusted server addresses when resolving domains for security reasons.

2. Install the Web Server for Chrome extension

  1. Navigate to the extension page for Web Server for Chrome
  2. Click on the Add to Chrome button.
  3. Select the CHOOSE FOLDER button, and select the folder where your project is located.
    chrome not allowed to load local resource
  4. Click on the address in the Web Server URL(s) menu to run the file.
Read more about this topic

  • FIX: Not enough memory to open this page in Google Chrome
  • How to fix slow Chrome in Windows 11
  • Microsoft Edge for Chromebook: How to Download & Install

3. Clear your DNS host cache

  1. On your browser, type the address below and hit enter.
    chrome://net-internals/#dns
  2. Click the button to Clear host cache.
  3. Relaunch your browser and try re-accessing the resource.

When you browse the same domain repeatedly, Chrome employs DNS caching to speed up the site’s loading by mapping IP addresses from the cache.

Unfortunately, due to variances in IP addresses, Chrome DNS caching may create delays in loading the webpage when website admins change IP addresses. This is a good fix if your error is caused by JavaScript not allowed to load local resources.

How do you fix failed to load resource the server responded with a status of 404 Not Found?

If you are not a server admin, there is nothing you can do other than contact the admin. However, if you manage the server, you should give users appropriate permissions for files, folders, and directories as the case may demand.

Without the correct permissions, the user will be restricted and will get error messages like:

  • Not be allowed to load local resource HTML image
  • Not allowed to load local resource javascript
  • User not allowed to load local resource angular

How do I allow local access to Chrome?

  1. Hit the close button to shut down all open instances of your Chrome browser.
    chrome not allowed to load local resource
  2. Open your run dialogue using hotkeys Windows + R.
  3. Type the text below and hit enter.
    chrome.exe --allow-file-access-from-file

You sometimes have to read XML or JSON data saved in a local file during a project’s testing or creation phases of a new site. IIS or even IIS Express, and Visual Studio may be used to execute the test website.

Chrome doesn’t enable javascript to communicate with your local file systems by default, and if you attempt to do so, you will get this error message: XMLHttpRequest cannot load file:///C:/path/to/C:/Temp/testdata.json. Origin null is not allowed by Access-Control-Allow-Origin.

Note that you will have to try a different solution if you are not allowed to load local resource iframe, PHP, HTML, or Jquery.

You should have successfully resolved the error of Chrome not allowed to load local resources. Please note that these solutions are not in any particular order, and you should try whichever seems the easiest to implement.

This isn’t the only resource problem, and many reported Error loading this resource in Chrome message, but that issue can be easily fixed.

newsletter icon

Beginners who are fiddling with Chromium based programs often encountered the “Not allowed to load local resource” error message.

The main cause of the problem is the underlying V8 Javascript engine inside Chrome/Chromium. Designed for high-performance and security, it does not allow local resources to be loaded (so you don’t accidentally load malicious code). Instead, you will have to load Javascript scripts and libraries from another server.

“Not allowed to load local resource” error happens not only in Chrome but any other programs based off of Chromium that runs Javascript, such as NodeJS, Opera, Microsoft Edge, Electron, Atom, etc.

In this article, we’ll demonstrate a quick fix that you can use every time you encounter “Not allowed to load local resource”.

Method 1 : Disable Chrome built-in security measures

Now that we know what the error message actually means, we can formulate a solution to it.

If you’re just fiddling around, consider disabling this specific Chrome security measure.

Please note that the security exception exist for good reasons and trying to circumvent them isn’t a good idea, especially in production environment.

To disable “Not allowed to load local resource” exception, you will have to pass a few flags to the execution. The command should be something like this

/path/to/chrome_binary –allow-file-access-from-files -disable-web-securityCode language: JavaScript (javascript)

/path/to/chrome_binary can be quoted if it contains special characters.

image-20201009092304891

To make the parameters effective, there must not be another instance of chrome running. If you have chrome running already and start a new instance with the anti-SOP parameters, it will have no effect. Please make sure that all instances are closed, include instances without GUI as well.

Method 2 : Run a simple server serving static files

An alternative for disabling Chrome security features is running a simple server serving files from your local machine.

Sure, you can spin up a new remote machine for this purpose, but it would be overkill, and you have to deal with managing a full-fledged web server. On top of that, the latency adds one or two seconds every time you reload the page.

If you’re using Chrome or Chrome-based browsers, you can install Web Server for Chrome from the Chrome Web Store. The extension runs off-line and has the ability to spin off a simple server serving files from a local directory over the network through HTTP.

img

You can’t use PHP or any other web development stack in conjunction with it, but for static files, this extension works fine. Web Server for Chrome even supports CORS methods.

If you want to load dynamically created resources, you would have to spin up a full-fledged server. An easy solution is a bundled WAMP or LAMP stack like Laragon or Bitnami LAMP stack installer.

Remember to use the URL from your web server instead of a file URL (file://). You should also use HTTP URLs as HTTPs could cause mixed content security warnings.

FAQ

Which programs are affected by Not allowed to load local resource?

Any programs which uses Chromium core or V8 Javascript engine will be affected by this error. A non-comprehensive list : Chrome, Opera, Vivaldi, NodeJS, Atom, Visual Studio Core, etc.

How to quickly fix Not allowed to load local resource?

Run a web server and put your files in there. Use the URL to serve files through your web server, not the file:// URL.

What’s the cause of Not allowed to load local resourceu?

The error happens when Javascript is trying to access local files. Modern browsers like Chrome prohibits this behaviour as it can be used for malicious purpose.

Google Chrome Help

Sign in

Google Help

  • Help Center
  • Community
  • Google Chrome
  • Privacy Policy
  • Terms of Service
  • Submit feedback

Send feedback on…

This help content & information

General Help Center experience

  • Help Center
  • Community

Google Chrome

@eiriarte Thanks for sharing that, however that did not work. If I pack the files for the main process using webpack, even with the node configuration that you have said, I still get the same error.

I am sharing a workaround that I am using to get around the issue for others who land on this thread.

Instead of using es features which require babel to transpile them to work correctly in the main. js file, I separated these out into different files. In my main.js I do not use any features which require babel transpilation. So instead of import I use require. For code which was using es7 proposal features such as async, I moved that code to different files, within a folder called desktopServices (you could come up with a better name). I now run webpack to create a bundle for desktopServices and I reference this bundle in main.js.

const myshell = require('./dist/desktopServices').myShell;

My webpack.config.main.js file contains the following config.


let config = {
  target:'electron',
  entry:'./desktopServices/desktopServices.js',
  output:{
    path:path.resolve(__dirname, 'dist'),
    filename: 'desktopServices.js',
    publicPath:'/dist/',
    libraryTarget:'commonjs2'
  },
  resolve: {
    extensions:["",".js",".json"]
  },
  module: {
    noParse: /node_modules/json-schema/lib/validate.js/,
    loaders:[{
      test: /.js?$/,
      exclude: /node_modules/,
      loader: 'babel-loader'
    },
      {
        test: /.json/,
        loader: 'json-loader',
      },
    ],
  },
}

module.exports = config;

Not the cleanest way, but I guess this is the route I am taking for the time being till some of the es features I want to use get incorporated into node and don’t require babel transpilation.

  • MiniTool

  • MiniTool News Center

  • How to Fix Not Allowed to Load Local Resource in Google Chrome?

By Aurelie | Follow |
Last Updated February 01, 2023

google search

What does Not Allowed to Load the Local Resource mean and what can you do to get rid of this error? In this post on MiniTool Website, we will show you the detailed instructions on that. Follow the steps carefully, and this error will be gone.

Not Allowed to Load Local Resource

It is not new to encounter some errors when you are inspecting a webpage in your Chrome/Edge/Safari/Firefox. When you are loading local resources in your browser, an error message might pop up – Edge/Safari/Firefox/Chrome Not Allowed to Load Local Resource. This means that you will be blocked from viewing specific files, web pages, or web resources.

In this case, congratulations, you’ve come to the right place! We will try our best to find the easiest and most effective solutions for you!

When you are loading some specific files, you are also get error codes like DNS_PROBE_POSSIBLE, ERR_CONNECTION_REFUSED, ERR_NAME_NOT_RESOLVED, STATUS BREAKPOINT besides Not Allowed to Load Local Resource.

How to Fix Not Allowed to Load Local Resource?

Fix 1: Change DNS Settings

Sometimes, when your computer dynamically obtains a DNS address from your ISP, it will stop due to some reason thus causing Not Allowed to Load Local Resource Chrome. Using the Google DNS servers is proven fruitful to fix that:

Step 1. Press Win + R to evoke the Run box.

Step 2. Type ncpa.cpl and hit Enter to open Network Connections.

Step 3. Right-click on the network adapter that you use most frequently and choose Properties.

Step 4. In the Networking tab, choose Internet Protocol Version 4 (TCP/IPv4) and hit Properties.

Step 5. In the General tab, tick Use the following DNS server addresses and set Preferred DNS server to 8.8.8.8 and Alternate DNS server to 8.8.4.4.

change DNS Settings

Step 6. Check Validate settings upon exit and hit OK to apply the changes.

Fix 2: Clear DNS Host Cache

There is an inbuilt DNS server in Google Chrome to help improve the website loading speed. However, when the IP address of the website is changed, the cache will automatically load the previous IP address thus triggering Not Allowed to Load Local Resource File. Therefore, you can try to clear the host cache to see if it works.

Step 1. Open your Google Chrome and copy & paste chrome://net-internals/#dns into the address bar and then hit Enter.

Step 2. Tap on Clear host cache and relaunch your browser to access the resource you want to load.

hit Clear host cache

Fix 3: Install the Web Server Extension for Chrome

The Web Server for Chrome is an offline extension which helps ser the local files and webpages to network from a local folder. It is also helpful to solve Not Allowed to Load Local Resource.

Step 1. Go to Web Server for Chrome.

Step 2. Press Add to Chrome and hit Add app in the confirmation window.

ALT= hit Add app

Step 3. Hit CHOOSE FOLDER and then browse the folder where your project is located.

Step 4. Hit the address under Web Server URL(s) to run the file.

Fix 4: Disable Security Settings in Chrome

If none of the methods above doesn’t work for you, you can try to disable the security feature on your Chrome. This method is a little risky because your browser will be vulnerable to attacks after disabling this feature. Therefore, please make sure that the resource you are loading is not malicious.

Step 1. Open Google Chrome and click on the three-dot icon to open Settings.

Step 2. In Privacy and security, hit Security > No protection (not recommended).

hit Security

Step 3. In the confirmation windows, press Turn off.

About The Author

Aurelie

Position: Columnist

Aurelie is a passionate soul who always enjoys researching & writing articles and solutions to help others. Her posts mainly cover topics related to games, data backup & recovery, file sync and so on. Apart from writing, her primary interests include reading novels and poems, travelling and listening to country music.

Chrome is stopping some of its users from loading local resources on the browser. This resource can be an image, a PDF, or a text file. One of the main reasons for the error is misconfigured settings of the browser. In this post, we are going to talk about this and see what to do when Chrome is not allowed to load local resources.

Chrome not allowed to load local resource

If Chrome is not allowed to load local resources, the first thing you should do is restart the browser. In case, the issue is a result of some temporary glitches, restarting will be enough. However, if restarting the browser is to no avail, follow the steps given below.

  1. Turn off the Chrome Security Settings
  2. Change the DNS Settings
  3. Clear DNS Host Cache
  4. Install the Web Server Extension for Chrome
  5. Clear Chrome’s Cache and Browsing Data

Before your bgin, hard refresh the web page by pressing CTRL+F5 and see if ir helps.

1] Turn off the Chrome Security Settings temporarily

Chrome has the tendency to block and not load the image if it thinks it has some malicious elements. But there is a possibility that the algorithm that the browser uses to check for malware is at fault and your file is totally fine. In that case, we have to disable the security settings in Chrome and then load the file.

As we know that Chrome security should not be disabled, if you alter the setting, you are opening the path for the hacker. Therefore, make sure that the resource you are loading is malicious-free and after loading the file, make sure to turn the settings back on. Follow the prescribed steps to do the same.

  • Open Chrome browser on your computer.
  • Once it opens, in the top right corner of the Chrome window click on the three-dotted line and select Settings.
  • Click on Privacy and Security from the left pane of the Settings page.
  • Now, click on Security and here you should go to the No protection (not recommended) option.
  • Finally, turn off the toggle for No protection.

It would be better to turn on the security after you are done loading the resources.

2] Change the DNS Settings

google dns server

The function of the DNS (Domain Name System) is to translate the domain name to the IP address and the IP address to the domain name. Whenever users type domain names, like thewindowsclub.com, into the address bar of web browsers, the DNS finds the right IP address of that website. Once the DNS server finds the correct IP address, your required website will be accessed. If the computer is dynamically switching DNS, the Chrome browser may block it because of security concerns. So, we can use Google DNS servers to resolve the error. Here is how to do it.

  • Press Windows + R key to open the Run dialog box.
  • Type ncpa.cpl and press the Enter button to open Network Connections.
  • Right-click on the Network adapter and select Properties.
  • Here, select the Internet Protocol Version 4 (TCP/IPv4) option and select Properties.
  • Select Use the following DNS server addresses option and enter the following IP address.
    Preferred DNS server: 8.8.8.8
    Alternate DNS server: 8.8.4.4
  • Finally, click on the OK button to save the setting.

Hopefully, after configuring the Google DNS address the issue will be resolved.

3] Clear DNS Host Cache

Google Chrome has a built-in DNS cache server that will help us to improve the website loading speed. If the developer of the website has changed the IP address, the cache will automatically load the previous IP address and you may face the said error. Therefore, it is a good idea to clear the host cache and this will resolve the error.

  • Firstly, open the Chrome browser on your computer and enter the following string in the address bar.
chrome://net-internals/#dns
  • After hitting the Enter button, you will get the Clear host cache option.
  • When you click on that you have cleared the host cache file.

Now close Chrome and open it again and see if your problem is solved.

4] Install the Web Server Extension for Chrome

The Web Server is a Chrome extension that runs offline and it will help to serve files and webpages to the network from a local folder. So we can set up an HTTP server to resolve the said error. Follow the steps to install the extension.

  • Go to chrome.google.com to load the Web Server for the Chrome extension page.
  • Now, press the Add to Chrome button and it might be possible that it will ask you to sign in to Chrome to add the extension.
  • Once installed, open the extension.
  • Here, click the CHOOSE FOLDER button and browse your project folder.
  • Finally, click the address shown under the Web server URL and run the web server.

Hopefully, this will do the job for you.

5] Clear Chrome’s Cache and Browsing Data

Last but not least, if nothing worked, our last resort is clearing Chrome’s cache and browsing data. This is done to ensure that the peculiar behavior of the browser is not caused by corrupted data. In order to do the same, follow the steps given below.

  1. Open Google Chrome.
  2. Click on the three dots and then click on Settings.
  3. Go to the Privacy and Security tab from the left side of the window.
  4. Select Clear browsing data.
  5. Change the Time range to All time.
  6. Tick Browsing history, Cookies and other side data, and Cached images and files. You can also tick other boxes if required.
  7. Finally, click on Clear data.

You need to wait for the browser to clear all its data and then check if the issue is resolved.

Hopefully, you will be able to resolve the issue using the solutions mentioned above.

Read: Fix Error 0x80040902 during the Google Chrome update

How do I fix Chrome not allowed to load local resources?

If Chrome is not allowed to load resources, you should start troubleshooting by restarting the browser and the computer if the former doesn’t work. In case, restarting is to no avail, follow the solutions mentioned in this post to resolve the issue.

Read: Fix ERR_CONNECTION_RESET error on Chrome browser

How do I open a local file in Chrome?

It is pretty easy to open local files in Google Chrome. In order to do the same, open a new tab in Chrome, even though it is not mandatory to open a new tab, it’s a better practice, and then Ctrl + O, now go to the location where your files are stored and finally open it.

Also read: How to open Local Files on Chrome.

8 ответов

тег отправки <img src="c:imagesmypic.jpg"> приведет к тому, что пользовательский браузер получит доступ к изображению из своей файловой системы.
если вам нужно сохранить изображения в папке, расположенной в c:images, я бы предложил создать сервлет вроде images.jsp, который в качестве параметра принимает имя файла, затем устанавливает содержимое ответа сервлета на изображение /jpg и затем загружает байты изображения из местоположения сервера и ответе его на ответ.

Но что вы используете для создания своего приложения? это чистый сервлет? Spring? JSF?

Здесь вы можете найти информацию о том, как это сделать.

T.G
31 май 2014, в 13:55

Поделиться

В Chrome вы должны разрешить эту возможность с флагом времени выполнения —allow-file-access-from-files

Однако похоже, что существует проблема с текущими версиями Chrome (37, 38), где это не работает, если вы также не передаете флаг времени выполнения —disable-web-security

Это неприемлемое решение, за исключением, возможно, как краткосрочного обходного пути, но оно было идентифицировано как проблема:
https://code.google.com/p/chromium/issues/detail?id=379206

Roger
05 сен. 2014, в 19:11

Поделиться

Многие браузеры изменили свои политики безопасности, чтобы больше не разрешать чтение данных непосредственно из общих файлов или даже локальных ресурсов. Вам нужно либо разместить файлы где-нибудь, чтобы ваш экземпляр tomcat мог их обслуживать, и поместил «обычный» http-url в созданный вами html. Это может быть достигнуто либо предоставлением сервлета, который читает и предоставляет файл, помещающий файл в каталог, где tomcat будет обслуживать его как «статический» контент.

Brett Okken
31 май 2014, в 13:43

Поделиться

У вас есть две альтернативы:

Сначала нужно создать ServletImageLoader, который будет принимать в качестве параметра идентификатор вашего изображения (путь изображения или хэша), который вы будете использовать внутри Servlet для обработки вашего изображения, и он будет печатать ответ загрузите загруженное изображение с сервера.

Во-вторых, нужно создать папку внутри вашей папки ROOT приложения и просто сохранить относительный путь к вашим изображениям.

Mifmif
31 май 2014, в 12:28

Поделиться

Эта ошибка означает, что вы не можете напрямую загружать данные из файловой системы, потому что за этим стоят проблемы с безопасностью. Единственное решение, которое я знаю, это создание веб-службы для загрузки загрузочных файлов.

Harun Ergül
22 июль 2015, в 12:07

Поделиться

Понятие местоположения http и места на диске отличается. Что вам нужно сделать:

  • для загруженного файла summer.jpg
  • переместите это под известным (в приложение) место на диск, например c:imagessummer.jpg
  • вставить в запись db, представляющую изображение с текстом summer.jpg
  • чтобы отобразить его, используйте обычный <img src="images/summer.jpg" />
  • вам нужно что-то (например, apache), которое будет обслуживать c:images под вашим приложением /images. Если вы не можете сделать это, то в шаге 2 вам нужно сохранить где-то под вашим веб-корнем, например c:my-applicationsdemo-appbuildimages

cherouvim
31 май 2014, в 14:10

Поделиться

Вот простое решение expressjs, если вы просто хотите запустить это приложение локально, а безопасность не вызывает беспокойства:

В вашем файле server.js или app.js добавьте следующее:

app.use('/local-files', express.static('/'));

Это будет служить вашему корневому каталогу ENTIRE под /local-files. Излишне говорить, что это действительно плохая идея, если вы планируете развертывать это приложение в любом месте, кроме вашей локальной машины.

Теперь вы можете просто:

<img src="/local-files/images/mypic.jps"/> 

note: Я запускаю macOS. Если вы используете Windows, вам, возможно, придется искать и удалять «C: » из строки пути

Pedro Hoehl Carvalho
23 нояб. 2017, в 20:23

Поделиться

Не используйте ABSOLUTE PATH для обозначения имени изображения, например: C:/xamp/www/Archivos/images/templatemo_image_02_opt_20160401-1244.jpg. Вы должны использовать ссылку на свое местоположение в веб-сервере. Например, используя ../../Archivos/images/templatemo_image_02_opt_20160401-1244.jpg в зависимости от того, где выполняется ваш процесс.

user6147214
01 апр. 2016, в 23:46

Поделиться

Ещё вопросы

  • 0Передать переменную в директиву, которая ограничена атрибутом
  • 1Как получить доступ к встроенному классу ES6 во встроенном <script>
  • 0Вторая строка повреждена после нескольких вызовов realloc
  • 1Регулярное выражение для соответствия местным ссылкам уценки
  • 0php @ Azure Веб-сайт: не могу написать в% TMP%
  • 1Отдых не может быть разрешен к типу
  • 1Метка в Listview изменяет высоту и ширину после прокрутки
  • 0Orbit 1.4 против Flexslider: проблемы с каждым, пытаясь выбрать один
  • 1Как установить значения пользовательского элемента управления из класса
  • 0Использование пакетной переменной в запросе sqlcmd
  • 0Spring boot schema.sql не работает с файлом mysqldump
  • 0Математика: Хранение 11 значений в 1
  • 1Новый экземпляр программы создается при прикосновении к тегу NFC
  • 0jQuery: не (: проверено) не работает?
  • 1Самостоятельный ссылочный список в Python?
  • 1аккорд d3: текст по центру
  • 0Пользовательский интерфейс jQuery, сбрасываемый за пределы видимой области jScrollpane, ловит событие удаления
  • 0Enum не был объявлен
  • 0мне нужно получить три выбора для дня, месяца, года в одной переменной
  • 1Не удается найти элемент с помощью Selenium
  • 0Javascript не загружен в правильном порядке?
  • 1Не удается импортировать установленный пакет в среде Python3 ноутбука Jupyter
  • 0Mysql создать представление, связывающее две таблицы
  • 1Где находится MVC в веб-API?
  • 0Держи диалог div где я его положил
  • 0отправка почты с использованием бесплатной функции codignator, доставляемой как спам
  • 0Foreach с огненной базой
  • 0как отобразить моих пользователей из firebase с помощью angularjs
  • 0Отображение div во время выполнения кода JavaScript
  • 0Как я могу использовать кнопку WindowsFormApplication для переключения между двумя приложениями Windows (заставить их наверх)?
  • 1Как разбить строку на слова?
  • 0Почему метод setUserId не работает в сущности symfony2?
  • 1отображение изображения в столбце вида сетки на странице aspx с условием
  • 0Почтовый штемпель в PHP 5: проверьте, была ли почта отклонена или была успешной
  • 1Автобокс wth ++, — оператор в Java
  • 1Получение позиции указания элемента из localStorage
  • 0Попытка удалить вложенный объект в мангусте
  • 0PHP многомерный массив
  • 1Реагировать на родной плоский список, а не на ожидаемое поведение
  • 0проверка размера массива символов c ++
  • 0Рекомендуемая угловая практика для $ http в контроллере или сервисе
  • 1Публикация и подписка в обе стороны с использованием MQTT Python
  • 0Использование среза Javascript внутри углового выражения
  • 0Псевдокод для определения функции даты
  • 0Докер phpmyadmin после входа в систему: 504 Время ожидания шлюза
  • 0Водяной знак в mPDF (PHP) не работает правильно
  • 1Проблема с запуском файла класса java, содержащего зависимость Jsoup
  • 1колба — сессия юнит-тестирования с носом
  • 1Для чего используется метод queue.dequeue_up_to () в tenorflow.data_flow_ops?
  • 0Удалить дубликаты записей из таблицы, где идентификатор дублируется

Понравилась статья? Поделить с друзьями:
  • Nr4140 ошибки мерседес
  • Nr 4143 ошибка мерседес актрос
  • Nr 155 navien ошибка 02
  • Npmproxy dll как исправить ошибку
  • Npm исправить ошибки