Make localhost/... popup localhost:3000/ - javascript

I have a local file a.html as follows, which can be launched by https://localhost/a.html. by clicking on Open b, it can open another file b.html, then by Send button, it could send data by postMessage:
<html>
<body>
<p onclick="openWindow()">Open b</p>
<form>
<input type="button" value="Send">
</form>
<script>
function openWindow() {
var popup = window.open("https://localhost/b.html", "popup", "width=200, height=200");
// var popup = window.open("https://localhost:3000/#/new", "popup", "width=1000, height=1000");
var button = document.querySelector("form input[type=button]");
button.onclick = function(e) {
e.preventDefault();
e.stopPropagation();
popup.postMessage("hi, how are you?", popup.location.href);
}
}
</script>
</body>
</html>
Now, rather than opening https://localhost/b.html, I want to open a page https://localhost:3000/#/new served by a local application. So I uncomment the line var popup = window.open("https://localhost:3000/#/new", "popup", "width=1000, height=1000");. Then it raises an error while opening it:
Uncaught DOMException: Blocked a frame with origin "https://localhost" from accessing a cross-origin frame.
at HTMLInputElement.button.onclick (https://localhost/a.html:20:49)
So it seems that https://localhost/ and https://localhost:3000/ are considered as cross-origin.
Does anyone have any solution or workaround to make https://localhost/a.html open https://localhost:3000/#/new?
Edit 1: I use Mac. Actually when going to production, everything will be put under a same domain www.myexample.com, which has static files like a.html and runs a server. I just want to have an easy solution for development in localhost in Mac.
Edit 2: A limitation is that, I have to open a.html by https://localhost/a.html; I am NOT allowed to use http or serve it as a static file (ie, https://localhost:3000/a.html).

You have mentioned you're using MEAN stack, so I assume you are using ExpressJS.
It's possible to serve static (for development): see http://expressjs.com/en/starter/static-files.html
Do NOT use https on localhost... It makes nothing more secure and just add an unneeded self-signed certificate.
For a more generic solution, nginx can be used to serve static files and pass other paths to the backend.

One solution is open Chrome in a terminal with some special arguments:
open -a Google\ Chrome --args --disable-web-security --user-data-dir=/Users/SoftTimur/Desktop/user-data-dir
I have also tried some Chrome add-ins, which did NOT work for my tests.
It will be great if we have a solution (eg, some setting) without having to open Chrome from a terminal each time...

Related

Eel application: download files in Browser

i´m currently using JavaScript and HTML with eel and Python. But unfortunately when I am trying to create a file in the Chrome-Browser window (as an download) over JS i can only download it once.
The second "download" is not working.
-> Chrome just shows this (as it does when it downloads something) but then nothing happens:
When I am using Edge browser or only JS without eel it works perfectly fine!
My JS function that creates the download: (string is a json string that is generated earlier).
var jsonLink = document.getElementById("jsonLink");
jsonLink.download = "exportedToJson.json";
jsonLink.href = "data:application/json;charset=utf-8," + encodeURIComponent(string);
Ok I found a solution:
My chrome browser was blocking more than one download from "localhost:8000". So I had to go to settings and allow more than one download.
Maybe this helps someone :)
Why did I not find this earlier:
When I started my Python script, it calls:
eel.start('index.html', mode='chrome', port=8000) #starting chrome
Which does open a new Chrome Tab without the Tabbar (so i did neither see the tabs nor my favorite sites). Therefore I did not get a notification when chrome stated that download is blocked.
But after starting the eel-local webserver and open localhost:8000 in my normal chrome window, I did get a notification and I was able to allow the downloads.
-> afterwards it also worked in this eel-chrome window.

JavaScript - How to pass input values from popup to parent window in Chrome?

I have an HTML page that contains a button says "Open Popup". Once this button is clicked, a popup window opens (using window.open).
The new popup window is an HTML page that contains a simple input filed and a submit button. Once the submit button is clicked, the popup window should close, and the text that's just been typed in the input field should now be displayed in the parent window.
I've tried doing it using opener.document.getElementById. It works perfectly in Firefox, but not in Chrome.
This is the code of my parent page (parent.html):
<!DOCTYPE html>
<html>
<body>
<button type="button" onclick="openPopup()">Open Popup</button>
<p id="result"></p>
<script type="text/javascript">
function openPopup() {
var popupWindow = window.open('popup.html', '', 'width=300, height=200');
}
</script>
</body>
</html>
And this is the code of my popup (popup.html):
<!DOCTYPE html>
<html>
<body>
<input type="text" id="userText" placeholder="Please enter some text">
<button type="button" onclick="submitText()">Submit!</button>
<script type="text/javascript">
function submitText() {
opener.document.getElementById('result').innerHTML = 'The text you\'ve entered is: ' + document.getElementById('userText').value;
self.close();
}
</script>
</body>
</html>
Note: Both parent and popup files are located in my desktop.
As mention, it works in Firefox, but not in Chrome. When I click the "Submit!" button in Chrome, nothing happens, and the following error shows up in the console:
Uncaught DOMException: Blocked a frame with origin "null" from accessing a cross-origin frame.
I spent hours trying to find help online, but I still can't make Chrome pass data from popup window to parent page (which both are, as mentioned, located in my desktop, i.e. in the same directory).
Thanks in advance.
What you are encountering is a security feature of Chrome that is applying a web security standard called CORS (Cross-Origin Request Specification). It's meant to prevent one website from accessing another (because this is a common technique to try and trick people into giving up personal information), unless both the pages originate from the same domain. For example, http://domainA.com shouldn't be able to communicate with http://domainB.com by default. In situations were this is a legitimate need, server configuration is required to allow it.
Because you are running your tests from your desktop (without a web server) no domain information is present and Chrome thinks you are making a Cross-Origin Request.
If you run your files from a web server (over http or https), it will work.
There are many free web servers available for you to set up on your local machine and many development tools incorporate their own web servers. For example, VS code and Visual Studio are both free and have web servers included.

How to make a 'protocol' of my own and a Desktop application to use it for a Browser? [duplicate]

How do i set up a custom protocol handler in chrome? Something like:
myprotocol://testfile
I would need this to send a request to http://example.com?query=testfile, then send the httpresponse to my extension.
The following method registers an application to a URI Scheme. So, you can use mycustproto: in your HTML code to trigger a local application. It works on a Google Chrome Version 51.0.2704.79 m (64-bit).
I mainly used this method for printing document silently without the print dialog popping up. The result is pretty good and is a seamless solution to integrate the external application with the browser.
HTML code (simple):
Click Me
HTML code (alternative):
<input id="DealerName" />
<button id="PrintBtn"></button>
$('#PrintBtn').on('click', function(event){
event.preventDefault();
window.location.href = 'mycustproto:dealer ' + $('#DealerName').val();
});
URI Scheme will look like this:
You can create the URI Scheme manually in registry, or run the "mycustproto.reg" file (see below).
HKEY_CURRENT_USER\Software\Classes
mycustproto
(Default) = "URL:MyCustProto Protocol"
URL Protocol = ""
DefaultIcon
(Default) = "myprogram.exe,1"
shell
open
command
(Default) = "C:\Program Files\MyProgram\myprogram.exe" "%1"
mycustproto.reg example:
Windows Registry Editor Version 5.00
[HKEY_CURRENT_USER\Software\Classes\mycustproto]
"URL Protocol"="\"\""
#="\"URL:MyCustProto Protocol\""
[HKEY_CURRENT_USER\Software\Classes\mycustproto\DefaultIcon]
#="\"mycustproto.exe,1\""
[HKEY_CURRENT_USER\Software\Classes\mycustproto\shell]
[HKEY_CURRENT_USER\Software\Classes\mycustproto\shell\open]
[HKEY_CURRENT_USER\Software\Classes\mycustproto\shell\open\command]
#="\"C:\\Program Files\\MyProgram\\myprogram.exe\" \"%1\""
C# console application - myprogram.exe:
using System;
using System.Collections.Generic;
using System.Text;
namespace myprogram
{
class Program
{
static string ProcessInput(string s)
{
// TODO Verify and validate the input
// string as appropriate for your application.
return s;
}
static void Main(string[] args)
{
Console.WriteLine("Raw command-line: \n\t" + Environment.CommandLine);
Console.WriteLine("\n\nArguments:\n");
foreach (string s in args)
{
Console.WriteLine("\t" + ProcessInput(s));
}
Console.WriteLine("\nPress any key to continue...");
Console.ReadKey();
}
}
}
Try to run the program first to make sure the program has been placed in the correct path:
cmd> "C:\Program Files\MyProgram\myprogram.exe" "mycustproto:Hello World"
Click the link on your HTML page:
You will see a warning window popup for the first time.
To reset the external protocol handler setting in Chrome:
If you have ever accepted the custom protocol in Chrome and would like to reset the setting, do this (currently, there is no UI in Chrome to change the setting):
Edit "Local State" this file under this path:
C:\Users\Username\AppData\Local\Google\Chrome\User Data\
or Simply go to:
%USERPROFILE%\AppData\Local\Google\Chrome\User Data\
Then, search for this string: protocol_handler
You will see the custom protocol from there.
Note: Please close your Google Chrome before editing the file. Otherwise, the change you have made will be overwritten by Chrome.
Reference:
https://msdn.microsoft.com/en-us/library/aa767914(v=vs.85).aspx
Chrome 13 now supports the navigator.registerProtocolHandler API. For example,
navigator.registerProtocolHandler(
'web+custom', 'http://example.com/rph?q=%s', 'My App');
Note that your protocol name has to start with web+, with a few exceptions for common ones (like mailto, etc). For more details, see: http://updates.html5rocks.com/2011/06/Registering-a-custom-protocol-handler
This question is old now, but there's been a recent update to Chrome (at least where packaged apps are concerned)...
http://developer.chrome.com/apps/manifest/url_handlers
and
https://github.com/GoogleChrome/chrome-extensions-samples/blob/e716678b67fd30a5876a552b9665e9f847d6d84b/apps/samples/url-handler/README.md
It allows you to register a handler for a URL (as long as you own it). Sadly no myprotocol:// but at least you can do http://myprotocol.mysite.com and can create a webpage there that points people to the app in the app store.
This is how I did it. Your app would need to install a few reg keys on installation, then in any browser you can just link to foo:\anythingHere.txt and it will open your app and pass it that value.
This is not my code, just something I found on the web when searching the same question. Just change all "foo" in the text below to the protocol name you want and change the path to your exe as well.
(put this in to a text file as save as foo.reg on your desktop, then double click it to install the keys)
-----Below this line goes into the .reg file (NOT including this line)------
REGEDIT4
[HKEY_CLASSES_ROOT\foo]
#="URL:foo Protocol"
"URL Protocol"=""
[HKEY_CLASSES_ROOT\foo\shell]
[HKEY_CLASSES_ROOT\foo\shell\open]
[HKEY_CLASSES_ROOT\foo\shell\open\command]
#="\"C:\\Program Files (x86)\\Notepad++\\notepad++.exe\" \"%1\""
Not sure whether this is the right place for my answer, but as I found very few helpful threads and this was one of them, I am posting my solution here.
Problem: I wanted Linux Mint 19.2 Cinnamon to open Evolution when clicking on mailto links in Chromium. Gmail was registered as default handler in chrome://settings/handlers and I could not choose any other handler.
Solution:
Use the xdg-settings in the console
xdg-settings set default-url-scheme-handler mailto org.gnome.Evolution.desktop
Solution was found here https://alt.os.linux.ubuntu.narkive.com/U3Gy7inF/kubuntu-mailto-links-in-chrome-doesn-t-open-evolution and adapted for my case.
I've found the solution by Jun Hsieh and MuffinMan generally works when it comes to clicking links on pages in Chrome or pasting into the URL bar, but it doesn't seem to work in a specific case of passing the string on the command line.
For example, both of the following commands open a blank Chrome window which then does nothing.
"c:\Program Files (x86)\Google\Chrome\Application\chrome.exe" "foo://C:/test.txt"
"c:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --new-window "foo://C:/test.txt"
For comparison, feeding Chrome an http or https URL with either of these commands causes the web page to be opened.
This became apparent because one of our customers reported that clicking links for our product from a PDF being displayed within Adobe Reader fails to invoke our product when Chrome is the default browser. (It works fine with MSIE and Firefox as default, but not when either Chrome or Edge are default.)
I'm guessing that instead of just telling Windows to invoke the URL and letting Windows figure things out, the Adobe product is finding the default browser, which is Chrome in this case, and then passing the URL on the command line.
I'd be interested if anyone knows of Chrome security or other settings which might be relevant here so that Chrome will fully handle a protocol handler, even if it's provided via the command line. I've been looking but so far haven't found anything.
I've been testing this against Chrome 88.0.4324.182.
open
C:\Users\<Username>\AppData\Local\Google\Chrome\User Data\Default
open Preferences then search for excluded_schemes you will find it in 'protocol_handler' delete this excluded scheme(s) to reset chrome to open url with default application

Using iframe with local files in Chrome

I am having a tough time figuring out how to access a page loaded in an iframe from the outer page. Both pages are local files, and I'm using Chrome.
I have an outer page, and many inner pages. The outer page should always display the page title for the inner page (it makes sense in my application, perhaps less so in this stripped-down example). This works without any problem in AppJS, but I've been requested to make this app work directly in the browser. I'm getting the error "Blocked a frame with origin "null" from accessing a frame with origin "null". Protocols, domains, and ports must match.".
I think this is due to Chrome's same origin policy regarding local files, but that hasn't helped me fix the problem directly. I can work around the issue in this stripped-down example by using the window.postMessage method per Ways to circumvent the same-origin policy. However, going beyond this example, I also want to manipulate the DOM of the inner page from the outer page, since this will make my code much cleaner - so posting messages won't quite do the job.
Outer Page
<!DOCTYPE html>
<html>
<head>
<meta name="viewport">
</head>
<body>
This text is in the outer page
<iframe src="html/Home.html" seamless id="PageContent_Iframe"></iframe>
<script src="./js/LoadNewPage.js"></script>
</body>
</html>
Inner Page
<!DOCTYPE html>
<html>
<head>
<title id="Page_Title">Home</title>
<meta name="viewport">
</head>
<body>
This text is in the inner page
</body>
</html>
JavaScript
var iFrameWindow = document.getElementById("PageContent_Iframe").contentWindow;
var pageTitleElement = iFrameWindow.$("#Page_Title");
Per Is it likely that future releases of Chrome support contentWindow/contentDocument when iFrame loads a local html file from local html file?, I tried launching Chrome with the flag
--allow-file-access-from-files
But there was no change in the results.
Per Disable same origin policy in Chrome, I tried launching Chrome with the flag
--disable-web-security
But again there was no change in the results.
Per What does document.domain = document.domain do?, I had both pages run the command
document.domain = document.domain;
This resulted in the error "Blocked a frame with origin "null" from accessing a frame with origin "null". The frame requesting access set "document.domain" to "", but the frame being accessed did not. Both must set "document.domain" to the same value to allow access."
For fun, I had both pages run the command
document.domain = "foo.com";
This resulted in the error "Uncaught Error: SecurityError: DOM Exception 18".
I'm floundering. Any help from more knowledgeable people would be fantastic! Thanks!
I'm sorry to say you that I've tried during weeks to solve this issue (I needed it for a project) and my conclusion is that it's not possible.
There are a lot of problems arround local access through javascript with chrome, and some of them can be solved using --allow-file-access-from-files and --disable-web-security, including some HTML5 offline features, but I definitely think there's no way to access local files.
I recomend you not to lose your time trying to circunvend this and to try to post messages wich you can interpret into the inner pages, so you can do the DOM modifications there.
Per our discussion in my cube just a minute ago :)
I hit this same problem (Ajax post response from express js keeps throwing error) trying to get an AJAX post request to work correctly.
What got me around it is not running the file directly off the file system but instead running it from a local server. I used node to run express.js. You can install express with the following command: npm install -g express
Once that is accomplished, you can create an express project with the following command: express -s -e expressTestApp
Now, in that folder, you should see a file named app.js and a folder named public. Put the html files you wish to work with in the public folder. I replaced the file app.js with the following code:
var express = require('/usr/lib/node_modules/express');
var app = express();
app.use(function(err, req, res, next){
console.error(err.stack);
res.send(500, 'Something broke!');
});
app.use(express.bodyParser());
app.use(express.static('public'));
app.listen(5555, function() { console.log("Server is up and running"); });
Note, the require line may be different. You have to find where your system actually put express. You can do that with the following command: sudo find / -name express
Now, start the express web server with the following command: node app.js
At this time, the webserver is up and running. Go ahead and open a browswer and navigate to your ip address (or if you're on the same machine as your server, 127.0.0.1). Use the ip address:portnumber\filename.html where port number is the 5555 in the app.js file we created.
Now in that browser, you shouldn't (and didn't when we tested it) have any of these same problems anymore.
file:// protocol and http:// protocol make things to behave very differently in regards to iframes. I had the same issues you describe with an app on PhoneGap which uses file protocol to access all local files within the local assets/www folder.
If seems that modern browsers prevent the display of "local" files using the file protocol in iframes for security reasons.
We ended up dumping iframes and just using divs as "viewports". Fortunately the overall size of our app was not that big so we managed to load everything in a single page.

Executing javascript from within an iframe

I have:
A web server (server 1)
An application server running some beast of a legacy web app (server 2)
An iframe on server 1 pulling in the application from server 2
My problem is:
The legacy app uses JS validation on its forms. When a user attempts to submit an incomplete form, an alert pops up to notify the user that they are a dummy. Of course, this fails when the app is run inside of an iframe because server 1 and server 2 live at different domains.
I tried setting the following proxy directives on server 1:
ProxyPass /legacy_app http://server2.url/legacy_app
ProxyPassReverse /legacy_app http://server2.url/legacy_app
I'm now able to serve the iframe from http://server1.url/legacy_app, but I'm still unable to execute javascript inside that iframe -- I get the same security/access errors as I did when the app was running on a different domain.
Is there something else I can try?
How is the legacy app checking if the boxes are filled in? Simple javascript? Ajax?
The alert box itself should still work. I'm thinking the code for determining if the alert should be issued might be what's broken.
Running the following code on my local apache server still gives me the alert onLoad even though the page is on a remote host:
<html>
<body>
<div>
<iframe src="http://www.crowderassoc.com/javascript/alertbox.html" width="300" height="200">
</div>
</body>
</html>
Try copying the above code to a page on server #1 and see if you get the alert box from that remote site in the iframe.
Have you tried hosting the script inside of a .js file hosted on server #1 but running out of the iframe (referenced out of server #2)?
I think a browser is okay with referencing an external site, but doesn't like it when it is referenced by an external site.
Haven't tried it myself, but I believe that's how I've heard of this sort of a problem being worked around. I know this is the method that Google Analytics uses - you have to request the .js file from Google's servers, but once it's there, it has access to the browser.
Joe, I think you are correct. A quick test with other servers shows that I can trigger alerts from remotely-hosted scripts quite easily.
The legacy server is the client's and we don't have easy access to it, but glancing at their JS it looks like they're doing some sort of cross-site/framing detection -- worth further investigation.
I've had this situation in the past where I was trying to build an app around a heavily scripted pre-existing app on a remote server, and the app would run fine if it was opened in its own window, but if I tried loading it into a frame, it would break.
What I ended up doing for this project was opening the local application in a pop-up with a width of 495px, loading the external app in the main (already existing) window, resizing the main external app window to the screen width minus 495px, and positioning the windows side by side on the screen. This gave the end user a similar effect to what I had been trying to do with frames, only it worked.
In case it helps, here is the code I used from my index.php file:
// Manipulating the current window
window.location.href = 'http://www.someExternalApp.com'; // setting the page location.
window.name = 'legacyapp'; // setting the window name just the for heck of it.
moveTo(0,0); // moving it to the top left.
// Resizing the current window to what I want.
mainWindowWidth = screen.width - 495;
mainWindowHeight = screen.height; // Makes the window equal to the height of the users screen.
resizeTo(mainWindowWidth,mainWindowHeight);
// function for opening pop-up
function openWin(){
win2 = window.open(page,'',winoptions);
win2.focus();
}
// internal app location (for use in pop-up)
page = 'someLocalApp.php';
// internal app Window Options (for pop-up)
winoptions = 'width=490,height='+mainWindowHeight+',top=0,left='+mainWindowWidth+'leftscrollbars=1,scrolling=1,scrollbars=1,resizable=1,toolbar=0,location=0,menubar=0,status=0,directories=0';
// Opens the local app pop-up
openWin();

Categories