Same-origin policy
You can’t access an <iframe>
with different origin using JavaScript, it would be a huge security flaw if you could do it. For the same-origin policy browsers block scripts trying to access a frame with a different origin.
Origin is considered different if at least one of the following parts of the address isn’t maintained:
protocol://hostname:port/...
Protocol, hostname and port must be the same of your domain if you want to access a frame.
NOTE: Internet Explorer is known to not strictly follow this rule, see here for details.
Examples
Here’s what would happen trying to access the following URLs from 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:80 -> Failure: different protocol
ftp://www.example.com:21 -> Failure: different protocol & port
https://google.com/search?q=james+bond -> Failure: different protocol, port & hostname
Workaround
Even though same-origin policy blocks scripts from accessing the content of sites with a different origin, if you own both the pages, you can work around this problem using window.postMessage
and its relative message
event to send messages between the two pages, like this:
-
In your main page:
const frame = document.getElementById('your-frame-id'); frame.contentWindow.postMessage(/*any variable or object here*/, 'https://your-second-site.example');
The second argument to
postMessage()
can be'*'
to indicate no preference about the origin of the destination. A target origin should always be provided when possible, to avoid disclosing the data you send to any other site. -
In your
<iframe>
(contained in the main page):window.addEventListener('message', event => { // IMPORTANT: check the origin of the data! if (event.origin === 'https://your-first-site.example') { // The data was sent from your site. // Data sent with postMessage is stored in event.data: console.log(event.data); } else { // The data was NOT sent from your site! // Be careful! Do not use it. This else branch is // here just for clarity, you usually shouldn't need it. return; } });
This method can be applied in both directions, creating a listener in the main page too, and receiving responses from the frame. The same logic can also be implemented in pop-ups and basically any new window generated by the main page (e.g. using window.open()
) as well, without any difference.
Disabling same-origin policy in your browser
There already are some good answers about this topic (I just found them googling), so, for the browsers where this is possible, I’ll link the relative answer. However, please remember that disabling the same-origin policy will only affect your browser. Also, running a browser with same-origin security settings disabled grants any website access to cross-origin resources, so it’s very unsafe and should NEVER be done if you do not know exactly what you are doing (e.g. development purposes).
- Google Chrome
- Mozilla Firefox
- Safari
- Opera: same as Chrome
- Microsoft Edge: same as Chrome
- Brave: same as Chrome
- Microsoft Edge (old non-Chromium version): not possible
- Microsoft Internet Explorer
Blocked a frame with origin from accessing a cross-origin frame is an error that you’ll see in the Google Chrome console when your code violates the “Same-origin Policy” (SOP). This article will explain why you’re seeing this error and how you can get rid of it.
Throughout this article, we’ll explain the fundamentals of “Same-origin Policy browser” restrictions and why web browsers like Google Chrome implement it. Now, you’re about to learn a lot, so grab your notebook, and let’s explain everything that you need to know about it.
Contents
- Why Did Google Chrome Block a Cross-origin Frame? Major Culprits
- – You Violated the Same-origin Policy (Sop)
- How To Fix the Cross-origin Error in Google Chrome? The Best Solutions
- – Host Your Code on a Server
- – Use “window.postmessage()” for Communication
- – Disable Same-origin Policy in Google Chrome
- Conclusion
Why Did Google Chrome Block a Cross-origin Frame? Major Culprits
Google Chrome blocked a “cross-origin frame” because you violated the Same-origin Policy. This policy is a security measure in Chrome and other web browsers that prevents a site from loading the content of another site if they don’t have the same origin i.e, the same port, protocol, and host.
– You Violated the Same-origin Policy (Sop)
When you violate the Same-origin Policy, that’s when Google Chrome will show the “uncaught DOMexception” that it blocked a frame. This error message means a code on your web page is trying to access a frame from another origin.
For example, the first part of the following HTML belongs to “test.html”, and it’s adding the “calculate_factorial.html” using an “<iframe>”. When you run the code, you can’t calculate the factorial using the form because it violates the Same-origin Policy.
<head>
<script>
function get_factorial(number){
var number_factorial = 1;
for (;number >0; number–) number_factorial *= number;
return number_factorial;
}
</script>
</head>
<body>
<frame>
<iframe id=”my-iframe-id” src=”calculate_factorial.html” height=”200″ width=”300″></iframe>
</frame>
</body>
<!– Code for “calculate_factorial.html” –>
<head>
<script>
function button_calc_factorial(){
let to_be_factorial = document.factorial_form.factorial_form_value.value;
let to_be_factorial_result = document.factorial_form.factorial_form_result;
try {
if (window.top.get_factorial == null)
throw “The factorial function does not exist.”;
if (to_be_factorial === “” || to_be_factorial.trim().length === 0)
throw “_Value cannot be empty.”;
if (isNaN(to_be_factorial))
throw “_You did not enter a number.”;
if (to_be_factorial < 0)
throw “_Only positive numbers are allowed.”;
to_be_factorial_result.value = window.top.get_factorial(document.factorial_form.factorial_form_value.value);
}
catch(exception){
if (typeof(exception) == “string”){
if (exception.charAt(0) == “_”){
alert(exception.substr(1));
to_be_factorial.focus();
to_be_factorial.select();
}
else console.log(exception);
}
else console.log(“Error: ” + exception.message);
}
}
</script>
</head>
<body>
<form action=”” name=”factorial_form”>
<input type=”text” name=”factorial_form_value” size=”3″ /> in factorial is:
<input type=”text” name=”factorial_form_result” size=”25″ /><br/>
<input type=”button” value=”Calculate Factorial” onclick=”button_calc_factorial()” />
</form>
</body>
How To Fix the Cross-origin Error in Google Chrome? The Best Solutions
You can fix the cross-origin error that appears in Google Chrome if you host your code on a server or use “window.postMessage()” to send messages between a parent document and a child iframe. If you’re in a development environment, you can disable the Same-origin Policy before you open Chrome.
– Host Your Code on a Server
We accessed our previous code example using the “file:///” protocol, and that’s why the Same-origin Policy blocked JavaScript from accessing the iframe.
The first solution is to host the code on a server, and by doing this, the JavaScript and the “< iframe>” will have the same origin, and your web browser will allow the communication. To host the code on a server, do the following:
- Download XAMPP from Apache Friends.
- Install XAMPP and launch the XAMPP control panel.
- Locate the “htdocs” folder in your XAMPP installation.
- Create a new folder in the “htdocs” folder and move your HTML code to this folder.
- Start the Apache server via the XAMPP control panel.
- Navigate to your project folder using “http://localhost/your_project_folder”.
- Try the calculator, and it will work without a cross-origin error.
Alternatively, you can host the code on GitHub Pages. To do this, use the following steps:
- Sign up for a GitHub account.
- Log in to your account and create a new repository.
- Upload your files to this new repository.
- Navigate to the “Settings” tab of the repository.
- Scroll down and turn on “GitHub Pages”.
- Wait for the process to complete, and you’ll get a GitHub Pages URL that points to a live version of the files in your repository.
- Access the main page that’s loading the calculator via the “< iframe>” and it should work.
– Use “window.postmessage()” for Communication
The “window.postMessage()”, can allow you to safely pass information between documents that have the same or different origins (cross-origin). Unlike the previous code that you had to host on a server for it to work, with “window.postMessage()”, the code will work with and without a server.
For example, the following contains code for two HTML documents; you can fill the form in “parent_frame.html” and it will show in “child_frame.html”. If you’re running this without a server, the origin will be “null”, else it will be the address of the web server.
<head>
<title>Parent Frame HTML</title>
</head>
<body>
<form id=”msg_form” action=”/”>
<input type=”text” id=”your_msg” value=”Your message”>
<input type=”submit” value=”postMessage”>
</form>
<frame>
<iframe id=”my-iframe-id” src=”child-frame.html” height=”200″ width=”300″></iframe>
</frame>
</body>
<script>
window.onload = function () {
let my_iframe = document.querySelector(“#my-iframe-id”).contentWindow;
let form = document.querySelector(“#msg_form”);
let your_msg = document.querySelector(“#your_msg”);
your_msg.select();
form.onsubmit = function () {
// The second value of postMessage should the
// name of your website. Here, we pass “*” so that
// it can work on your computer.
my_iframe.postMessage(your_msg.value, “*”);
return false;
};
};
</script>
<!– Code for “child_frame.html” –>
<head>
<meta charset=”utf-8″>
<Title>Child Frame HTML</title>
<script>
function displayMessage_NOT_SECURE (event) {
// This function is not safe. Use it on your computer only.
// A safer version will validate the origin
let message = “New message: ” + event.data + ” from ” + event.origin;
document.getElementById(“inbox”).innerHTML = message;
}
if (window.addEventListener) {
window.addEventListener(“message”, displayMessage_NOT_SECURE, false);
}else {
window.attachEvent(“onmessage”, displayMessage_NOT_SECURE);
}
</script>
</head>
<body>
<p id=”inbox”>You have no new message!</p>
</body>
– Disable Same-origin Policy in Google Chrome
“Disabling same-origin” in Google Chrome will allow cross-origin communications, but you should only do it for testing purposes.
There are two commands that you can use to disable the Same-origin Policy in Google Chrome, and the steps below show you how to use them on Microsoft Windows:
- Use “Windows key” and “R” on your keyboard to launch the “Run” dialog box.
- Disable the Same-origin in older versions of Chrome: chrome.exe –user-data-dir=”C:/dev session” –disable-web-security
- Disable the Same-origin Policy in newer versions of Chrome (version 103+): chrome.exe –disable-site-isolation-trials –disable-web-security –user-data-dir=”C:/dev session”
When you execute either of the previous commands, you’ll start Chrome in a confined sandbox, and you’ll see a warning that you can ignore. Also, you’ll find all the data for this isolated Chrome in the folder “dev session” under the “C:/” drive, so when you’re done it’s best to delete this folder.
Finally, you can now run the first code example in this article (without a server), and it will work because cross-origin communication is now allowed by default.
Conclusion
This article explained why Google Chrome and other web browsers block cross-origin communications and what you can do to allow or prevent the error. The following are the highlights of our discussion:
- The Same-origin Policy is why Google Chrome blocked your JavaScript code from accessing a cross “origin frame” on your web page.
- You can use “windows.postMessage()” for cross-origin communications with and without a server.
- If Google Chrome blocks your JavaScript code for violating the Same-origin Policy, host your code on a web server (local or GitHub Pages).
- For testing purposes, you can disable the Same-origin Policy in Chrome using the “–disable-site-isolation-trials” and “–disable-web-security” flags.
- When you’re using “windows.postMessge()”, always validate the origin of the message before using it on your web page.
Now, you know how cross-origin communications work and how to use it in Google Chrome. Use your new knowledge to become a better developer and teach others about the Same-origin “Policy browser” restrictions.
- Author
- Recent Posts
Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL. Meet The Team
Содержание
- Blocked a frame with origin . from accessing a cross-origin frame. #10
- Comments
- Footer
- Uncaught DOMException: Blocked a frame with origin «http://localhost:9009» from accessing a cross-origin frame. #7215
- Comments
- WebSite X5 Help Center
- Как устранить ошибку «blocked a frame with origin. a cross origin frame»
- Same author posts
Blocked a frame with origin . from accessing a cross-origin frame. #10
Hello, I think the library is great for managing twitter login, but I have a problem, when I want to use the component to make the login, I get the following error Error: Blocked a frame with origin» http: // localhost: 3000 » from accessing to cross-origin frame. In my specific case I am using my localhost` to be able to use proof of concept, and I enabled the cors, but I can not make it work. Is there any indication on this? or I’m doing something wrong when using the library
The text was updated successfully, but these errors were encountered:
This should be working. Also in example folder you can find an example with Node.js/Express.js application and React application. Both are hosted on localhost , but on two separate ports. Also i’ve created tutorial that explains similar setup.
You shouldn’t have any issues.
I currently manage a project in which everyone has work with their own server (backend and frontend), the part of the backend worked excellent for me, but when using the react component, I see that a window.open is created, to be able to open the twitter registration window, when entering the polling that window has problems with the cors permissions, so that part is the one that has stopped me, both on the backend server (api), as in the client enable the cors permission as you have it in the tutorial and I could not pass the setInterval cycle, some recommendation ?? , thanks for answering
Sorry for late response, but you should not have any other configuration for cors in frontend. Pay attention that you have correctly set up cors on backend.
Hello, I get the same issue, and my cors in the backend are correctly set. however the problem seems to come from the frontend that can not be able to get data from a popup without the same origine (like twitter.com). Did you found a workaround ?
I haven’t manage to reproduce this issue. Do you use latest version of library? What is the value for credentials prop that you are using?
I just need more information about the issue.
Ok, thanks for your quick answer.
Yes I download the last version of the library.
I tried with every possible value for credentials , but the error is still there.
But for me I don’t understant how it could work. I had read the code of your library and after some internet research, The parent window of a popup cannot access to anything from the popup if the origine of the popup is not the same that the parent window.
So if you try to get data like popup.location.hostname the browser will throw an error if the origin is not the same. I haven’t found any solution for this kind of problème.
If you need it, here is my call of the TwitterLogin.
I have removed the credential parameter because you do not use it in your examples.
I modified the component to use the callback offered by tweet, since it was impossible to obtain the token directly to authenticate
Thanks, I did it too, but I’d like to understand how it could work without modification.
I think it’s because of some change that twitter made in its way of authenticating
One question how do you end on different domain? Because, popup should go back to application. So I am creating popup from http://localhost:3000 and after authentication in popup will be opened http://localhost:3000/#callback? This is same host. What is your configuration for callback URL on Twitter application?
@josejaguirre, I’m experiencing the same issue, could you please elaborate a little bit on a workaround for it?
I used the process where the application redirects to a twitter login and then returns to the application using the callback I hope it serves you.
The steps you took were the following:
1.- Node Backend Use the library and create custom url for get request token from twitter link (https://api.twitter.com/oauth/request_token)
2.- React Component Edit getRequestToken from TwitterLogin and use the custom link and get the oauth_token prop
3.- React Component Redirect https://api.twitter.com/oauth/authenticate?oauth_token=$
4.- Twitter Setup Twitter app callback to return to your application
5.- Node Backend Setup authorization middleware using callback url.
@josejaguirre thank you for you response, I also use NodeJS, in fact I tried following through @ivanvs’s tutorial on implementing Twitter Authorization with React, however, I’m using KoaJS and had to use the oAuth module to authorize my ‘node-fetch’ requests — all seem to be working just fine, except for the frontend/react part.
Can you please explain what kind of customized link should be used in getRequestToken ? I’m fetching the following requestTokenUrl link http://localhost:8080/auth/twitter/reverse in getRequestToken and it does return an oauth_token which is passed to a popup with location of https://api.twitter.com/oauth/authenticate?oauth_token=$&force_login=$ .
My react app is running on port 3000, could the port difference be the reason causing the CORS issue?
@ivanvs you are right, it is working now, thank you. It’s clearly my gap in knowledge of what CORS really is.
Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘null’ is therefore not allowed access. If an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.
client React : https://localhot:3000
Expres server : https://localhot:4000 connect to server authentication
How i can fix by pass CORS ?
i try set header :
const customHeader = <>;
customHeader[‘Access-Control-Allow-Origin’] = ‘‘;
customHeader[‘Origin’] = ‘‘;
customHeader[‘Accept’] = ‘application/json’;
customHeader[‘Content-Type’] = ‘application/json’;
Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘null’ is therefore not allowed access. If an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.
client React : https://localhot:3000
Expres server : https://localhot:4000 connect to server authentication
How i can fix by pass CORS ?
i try set header :
const customHeader = <>;
customHeader[‘Access-Control-Allow-Origin’] = ‘‘; customHeader[‘Origin’] = ‘‘;
customHeader[‘Accept’] = ‘application/json’;
customHeader[‘Content-Type’] = ‘application/json’;
© 2023 GitHub, Inc.
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Источник
Uncaught DOMException: Blocked a frame with origin «http://localhost:9009» from accessing a cross-origin frame. #7215
Describe the bug
After updated storybook 3 to 5 the ‘actions addon’ throws CORS error when an action is performed. Figured out that setting the ‘depth’ option to 2 or less is a work around and no error appears. Posting bug report hoping any better solution may be found.
To Reproduce
Steps to reproduce the behavior:
- Initiate any action on storybook 5. CORS error appears in console.
Expected behavior
Actions should be performed.
Screenshots
N/A
Code snippets
I traced the bug to the following line:
This configuration fixes the issue. But it would be great to have this resolved and allow for display of action with greater depth of the object.
System:
- OS: MacOS
- Device: Macbook Pro 2018
- Browser: chrome
- Framework: react
- Addons: actions
- Version: 5.1.9
Additional context
This happened after upgrading from 3 to 5. Default webpack config is used. Babel was also upgraded to 7.
The text was updated successfully, but these errors were encountered:
This is still not resolved; should we re-open this or open a new issue?
Clicked actions like in the documentation are working in Chrome but not in firefox.
Currently seeing this DOMException in FireFox
SecurityError: Permission denied to access property «toJSON» on cross-origin object
Click the button above logs the event details in chrome but not in FireFox.
I opened a fix PR in telejson!
Crikey!! I just released https://github.com/storybookjs/storybook/releases/tag/v5.3.0-beta.8 containing PR #8940 that references this issue. Upgrade today to try it out!
You can find this prerelease on the @next NPM tag.
Closing this issue. Please re-open if you think there’s still more to do.
v5.3.0-beta.8 still has the Firefox bug for me. Version v5.3.9 also has the bug.
Version v6.0.0-alpha.1 also has the bug.
@zeorin could you check to see if the telejson dependency is actually updated in node_modules after installing?
Thank you for checking.
Will put this back on my todo list
@itsderek23 I don’t think it works with file URLs. you need to run a web server like npx http-server . works fine when served: https://storybook-design-system.netlify.app/
Head slap! Yes — that is it. For clarity, this works just fine:
@shilman is that known? I ask because that was not always the case before v6, you could easily build an instance, compress it and share it with others. I feel like it’s possible that a lot of people in this thread are running into this because it’s not being run on a local server for whatever reason.
@reywright This issue is still open, isn’t it? 😉 I think we were looking for a repro and the repro is to open built storybook from a file URL @ndelangen
I am also seeing this when trying to use Storybook Composition. It works fine within the original storybook, but I get the same error ( Uncaught DOMException: Blocked a frame with origin from accessing a cross-origin frame. ) at the same line whenever trying to load a story from the lower level «composed» storybook in the higher level «composing» storybook. Both storybook instances on 6.1.5, using basically stock webpack configs. If you’d like to verify/reproduce, here is a link to our Chromatic permalink. Anyone should be able to add this as a composed story and see the issue.
Anyone have ideas for a solution or workaround?
Источник
WebSite X5 Help Center
Как устранить ошибку «blocked a frame with origin. a cross origin frame»
При переходе на страницу заказа, выдает blocked a frame with origin. from accessing a cross origin frame. Как это устранить. Скорее всего воспринимает, что это другой сайт.
can you explain more clearly your problem please?
attach a screenshot and tell me the url of the site.
Вы можете объяснить более четко ваша проблема , пожалуйста?
прикрепить скриншот и скажите мне URL сайта .
Когда клиент заходит с со страници заказов, и переходит на оформление заказов выдает следующую ошибку. Я посмотрел по интернету, это из за того, что страница заказов прописывается с именем car/index Система воспринимает это как другой сайт и блокирует страницу заказов. Как мне устранить эту ошибку.
Страница сайта noribell.kz
i suppose that depends by the payment that you inserted in the ecommerce section.
I am sorry but i can not help you about this, try contact directly your back or payment service and ask a new code.
я полагаю , что зависит от оплаты , вставленной в разделе электронной коммерции .
Мне очень жаль, но я не могу помочь вам об этом , попробуйте контакт непосредственно спину или платежный сервис и задать новый код .
X5 каким боком ? На сайте всё работает — переход в корзину, оформление заказа.
Скан даёте с плеера метрики. Начните разбираться с Вебвизором http://oborot.ru/article/688/10
Все платежные инструменты стоят стандартные от Х5, и до системы оплаты не доходит, так как для этого нужно зайти на страницу оформления заказа,а туда клиенты не могут зайти, поисковая система сразу блокирует, так как у страницы заказов идет страница car/index, в поисковой системе яндекс, стоит правило, и система воспринимает страницу с index как попытку зайти другого сайта и блокирует.
Смысла разбираться с веб визором, если бы система работала,а веб визоре выдавала ошибку, то у меня бы оформляли заказы и приходило бы уведомление, что заказ оформлен, но этого нет. При чем тут вебвизор который только дает скрин того, что делает клиент.Я посмотрел все форумы,это дело не в вебвизоре,а в том, что у поисковой системы яндекс установленно правило,и она воспринимает расширение index как другой сайт который пытается зайти на мой.
При этом я со своего компьютера могу зайти и все работает,а вот заказать у меня не могут. Это ошибка в названии страницы заказов, ее можно же было сделать car/order или по другому, но что бы она не дублировала страницу сайта. Или как я могу ее изменить скриптами или другим способом.
Как сформулировали запрос в начале темы и потом дали скрин, такой и ответ получили. Ещё раз проверил: переход на страницу заказа работает, дальнейшее оформление без проблем.
Из последнего поста , похоже Ваша проблема на хостинге — нет обратной связи с клиентом, не приходят уведомления. Типичная проблема — пишите хостеру в тех.поддержку, обычно это проиходит на бесплатных.
Можете сделать WEBSITE TEST http://ваш домен/admin и проверить с крипты e-mail формы
- Italiano
- Español
- Deutsch
- Français
- Pусский
- Polski
- Português BR
English
This site contains user submitted content, comments and opinions and it is for informational purposes only. Incomedia disclaims any and all liability for the acts, omissions and conduct of any third parties in connection with or related to your use of the site. All postings and use of the content on this site are subject to the Incomedia Terms of Use.
Источник
Политика безопасности одинакового происхождения
Вы не можете получить доступ к <iframe>
с помощью Javascript, это может стать огромным недостатком безопасности, если вы сможете это сделать. Для политики того же происхождения браузеры блокируют скрипты, пытающиеся получить доступ к кадру с другим происхождением.
Происхождение считается другим, если не поддерживается хотя бы одна из следующих частей адреса:
<protocol>://<hostname>:<port>/path/to/page.html
Протокол, имя хоста и порт должны совпадать с вашим доменом, если вы хотите получить доступ к фрейму.
Примеры
Здесь произойдет попытка доступа к следующим 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
Обход
Несмотря на то, что политики одного и того же происхождения блокируют доступ к контенту сайтов с другим происхождением, , если у вас есть обе страницы, вы можете обойти эту проблему, используя window.postMessage
и его относительное событие message
для отправки сообщений между двумя страницами, например:
-
На главной странице:
var frame = document.getElementById('your-frame-id'); frame.contentWindow.postMessage(/*any variable or object here*/, '*');
-
В
<iframe>
(содержится на главной странице):window.addEventListener('message', function(event) { // IMPORTANT: Check the origin of the data! if (~event.origin.indexOf('http://yoursite.com')) { // The data has been sent from your site // The data sent with postMessage is stored in event.data console.log(event.data); } else { // The data hasn't been sent from your site! // Be careful! Do not use it. return; } });
Этот метод может применяться в в обоих направлениях, создавая слушателя на главной странице и получая ответы от фрейма. Та же логика также может быть реализована во всплывающих окнах и в основном в любом новом окне, создаваемом главной страницей (например, используя window.open()
) без каких-либо различий.
Отключение политики одного и того же происхождения в вашем браузере
Уже есть хорошие ответы на эту тему (я просто нашел их googling), поэтому для браузеров, где это возможно, я свяжу относительный ответ. Однако помните, что отключение политики одного и того же происхождения (или CORS) повлияет только на ваш браузер. Кроме того, при запуске браузера с отключенными настройками безопасности с одним и тем же источником доступ к ресурсам кросс-источника запрещен любым сайтом, поэтому он очень опасен и должен выполняться только для целей разработки.
- Google Chrome
- Mozilla Firefox
- Apple Safari: невозможно, только CORS.
- Опера: невозможно.
- Microsoft Edge: невозможно.
- Microsoft Internet Explorer: невозможно, только CORS.
Добрый вечер Supersumestria,
Конечно Вы наверняка вкурсе почему это происходит, но на всякий случай:
Same Origin Policy [RU Wiki] политика одного источника предотвращает доступ к большинству методов и свойств для страниц на разных сайтах. Это значит, что web-приложения, использующие такие API, могут запрашивать HTTP-ресурсы только с того домена, с которого были загружены, пока не будут использованы CORS-заголовки.
Может лучше добавить на ваш тестовый сервер эти самые CORS заголовки это совсем не сложно как мне кажется, по сравнению с поиском альтернативных решений. Но если Вы их найдете я буду рад если поделитесь.
Например на php сервере это сделать можно так
PHP | ||
|