Execute command on another tab - javascript

I'm new at JavaScript, so can someone help me? How can I execute a command on another tab? For example, I have opened new tab from my main tab and opened translate.com (just for textbox) on it, and the problem is I don't know how to put text in search textbox?
I open the page with this command:
var page = window.open('https://www.translate.com/');
On the page, I can enter text with this code:
$string1 = $("#source_text");
$string1.val("text");
I have tried this, but this code doesn't work the way I want it to.
var page = window.open('https://www.translate.com/');
setTimeout(function(){page.f1()},20000);
setTimeout(function(){page.close()},30000);
function f1() {
$string1 = $("#source_text");
$string1.val("ka tu");
}

I find the function that you are trying to run very abnormal. So, let's start with small steps.
The page.close() function is perfect you can do that and it works. The other part won't work first of all because the page object created by window.open has no function called f1 on it.
Furthermore it is very important from where you are trying to run the script on the other window you always must take into consideration the cross-origin limitations. Easily explained if you try to run a function from a google.com tab on a separate window yahoo.com it won't work this is a security issue.
In order to run function f1 in that window it is important that f1 function is declared globally and ussualy you try and do this the following way page.window.f1() - and there you have it. So for example your code would be
page.window.$("#source_text").val('something');
refactoring your code would be like this:
var page = window.open('https://www.translate.com/');
setTimeout(function(){ page.window.$("#source_text").val('something');},20000);
setTimeout(function(){page.close()},30000);
open translate.com in a tab open dev tools in chrome and paste the above code in the console tab and see the results, it will work.
I recommend that before running code in another window you should check that that window is loaded first of all (in your case works) because of the long timeout.
A better solution would be using HTML5's postMessage API: check this link here for a good tutorial: https://robertnyman.com/2010/03/18/postmessage-in-html5-to-send-messages-between-windows-and-iframes/ - also this meens of course that the window you are opening is listening for some sort of postMessages.
In general you do this things with hosts that you manage and not other hosts because it might not work always. Also it will always work if you are on a host and open the same host in another window otherwise you end up with this security error: VM88:2 Uncaught SecurityError: Blocked a frame with origin "https://some_other_host" from accessing a frame with origin "https://www.translate.com". Protocols, domains, and ports must match.
Hope this helps, and you understand the way it works now.
Cheers

Related

JS - tab triggering another tab to run the code

I'm working on small automation and encountered one problem. At first attempt I wanted to send CORS request from one web to another but it is restricted on the domain I'm automating (redirect is not allowed). In this case I have to open the origin page first and then send the request. I'm gonna open new window window.open and send the request from there (Checked and it works). I'd like to make it as simple as possible so to do it I need to control the new tab from current tab - Force it to run some lines of code. Is it even possible in modern js ?
It should be, you'd utilize something along the lines like:
var myWindow = window.open("", "_self");
myWindow.document.write("<p>I replaced the current window.</p>");
Control gets finicky but this should help.

When moving to new URL with Chrome console, is there a way to keep variables alive?

I'm totally new to JavaScript either Chrome console.
My search of the literature was not enough to answer the question.
But I found it is hard to find any previous questions which tell me "How to prevent variable flushing(?) when you move to new URL in Chrome console".
For example, Let's say right now I'm in Google Starting Page ("https://www.google.com/")
Then I open Chrome console, make integer variable and function like this...
a = 10
function myFunc(){
console.log("Hello")
}
After that, I move to Yahoo homepage with this code
this.document.location = "https://www.yahoo.com/"
Then, as you can expect, my previously defined variable and function are GONE.
When I try to call my previous variable a in Yahoo,
Uncaught ReferenceError: a is not defined
at <anonymous>:1:1
Until now I'm stuck on this problem.
I wonder how to tell browser to keep variables and functions alive whenever moving to new URL?
All you do in the console, you do in the context of the current page (its window global object and local scope). If you change the page, this context is gone.
But you can quickly re-initialize the state if you use a scratchpad script in the "Sources" tab (and "Snippets" subtab) of the developer tools. Just create a new script and press Ctrl+S. Then you can select "Run" in the context menu of this script each time the page is changed and the state will be re-created:
No you can't, however If you wanna "save" some values you can send them to your server (as ajax request with json) or put them as your link parameter e.g. https://your.server.com/save?a=valueOfA (of course that server must support this parameter and return response which will set proper values to proper variables)
you can use localStorge() to save data on client browser it wont work for function tho just wanted to mention it

Cross-origin security error when moving an application to a subdomain (2018)

Background information: We have a platform which runs on https://system.example.com. This platform consists of 10 separate web applications (all written in PHP and JS). Each application has historically been in a sub-directory within the same subdomain:
https://system.example.com/app1/
https://system.example.com/app2/
...
https://system.example.com/app10/
We are in the process of rebuilding one of the applications, app2, and have decided to host this on a new separate subdomain, https://app2.example.com.
Part of the app2 application uses JavaScript to open a pop-up window for app10. Most functionality inside this popup works as expected. However, when attempting to use a "Save" button inside the popup my browser console was showing:
Uncaught DOMException: Blocked a frame with origin "https://app2.example.com" from accessing a cross-origin frame.
at https://system.example.com/app10/manage.php:1:334
I have read both SecurityError: Blocked a frame with origin from accessing a cross-origin frame and https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage but still unclear as to how to fix this.
The code and process I have is as follows:
The popup is opened from https://app2.example.com by a button which has an onclick event handler:
<button onclick="postToPopUp('https://system.example.com/app10/manage.php', 'fileManage', 'width=800px,height=600px', ['f_id', '123'], 'app2', 'filesCallbackManage')">Open app10</button>
The postToPopup() function is used to pass POST data from app2 into https://system.example.com/app10/manage.php based on Javascript window.open pass values using POST - this works fine.
The problem occurs when I click a "Save" button inside the popup which renders the following markup within the popup window:
<!doctype HTML><html><head><title>upload</title>
<script type="text/javascript" language="javascript" charset="utf-8">
var fileObject = {"files":{"0":{"f_id":"1784","f_title":"test07.pdf"},"f_id":123}};
window.opener.filesCallbackManage(fileObject);
window.close();
</script><body></body></html>
What this did originally - when everything was under the same subdomain - was called a js function filesCallbackManage() which resided in the code for https://system.example.com/app2. The function itself was passed an object, fileObject, which updated various parts of the UI inside app2. The popup was closed after clicking the Save button due to window.close();
Although I've read about using postMessage I don't understand how this fits in or whether this is even the correct solution to my problem? The data is being posted from the subdomain https://app2.example.com to https://system.example.com/app10 correctly. The problem is that filesCallbackManage() won't fire because of the cross origin restriction. Inside my code for https://app2.example.com I have a simple statement to see if it's firing:
function filesCallbackManage(data)
{
console.log('filesCallbackManage has fired');
}
This never fires because of the problem I have. I get the console error mentioned previously and a blank popup window (technically this is correct since there is nothing in the <body> tag in the above markup) but the window doesn't close and the callback isn't fired.
The example given on the Mozilla website isn't extensive enough to understand how it can be adapted to this type of scenario. Please can someone elaborate? Furthermore, the linked Stack Overflow post is four years old so I want to be sure anything I put on this is secure and up-to-date.
The postToPopup() function is used to pass POST data
Submitting a form across origins is fine. So you can do this.
The problem occurs when I click a "Save" button inside the popup
You're trying to access the DOM of the window across origins. This is forbidden.
Although I've read about using postMessage I don't understand how this fits in or whether this is even the correct solution to my problem?
postMessage is as close as you can get to accessing the DOM of a window across origins.
You can't do this.
var fileObject = {"files":{"0":{"f_id":"1784","f_title":"test07.pdf"},"f_id":123}};
window.opener.filesCallbackManage(fileObject);
Instead you have to send a message:
window.opener.postMessage(fileObject, "https://system.example.com");
And have code which listens for it:
addEventListener("message", receiveMessage);
function receiveMessage(event) {
if (event.origin !== "http://app2.example.com") { return false; }
filesCallbackManage(event.data);
}

Error: Could not complete the operation due to error 8150002e

I am working on a Outlook VSTO add-in, in which I am using 'System.Windows.Forms.WebBrowser' to display the add-in functionality.
One functional requirement is to have oauth connection to cloud accounts (like OneDrive, Dropbox). When user clicks a button (e.g. 'Connect OneDrive'), we call 'window.open' in JavaScript code (ES6) with the oauth-url.
The issue which I am facing is, if user doesn't enter any credentials and close the window, and then again try to connect the cloud account (by clicking the 'Connect OneDrive'), I am getting an exception (Error: Could not complete the operation due to error 8150002e.).
I couldn't find any information about the error code '8150002e' on web.
This exception is not always present but comes around 50% of the times.
Any help would be appreciated in this.
what I have tried:
changing the windowName param every time window.open is called
having global var for window Object.
Using _blank parameter to open a new window every time.
After 5-6 times, the error comes up, after 5-6 times error goes away and auth window start coming up like before.
Opening a simple static HTML page in 'window.open' to verify if the issue has something to do with HTML page. The above issue is still present.
Resetting the System.Windows.Forms.WebBrowser programmatically.
Removing the cookies.
Instead of calling window.open from JavaScript code, we call VSTO code to open the browser window, the error is still there.
Edit: Created a minimal viable example at
https://github.com/vinay-x/SampleAddin
Code related to the issue:
SDXOLForm1.cs (navigates the browser to SamplePage.HTML hosted on localhost:8001)
SamplePage.HTML (contains a button, which calls window.open function).
The sample application has a windows form which contains a webBrowser control, which navigates to a simple HTML page which contains a button.
Had to deal with some IE11 stuff and I ran across this question. The solution I found to fix this issue is to set the window variable to null prior to calling window.open.
So for your example you have this:
function myFunction() {
window.open("https://www.w3schools.com", 'BackfliptOAuth', "width=800,height=800,center=true,useContentSize=true");
}
I modified it to this:
var win = null;
function myFunction() {
win = null;
win = window.open("https://www.w3schools.com", 'BackfliptOAuth', "width=800,height=800,center=true,useContentSize=true");
}

Need to refresh a single ie7 web tab from command line

I need to create a batch file that will stop a process and then refresh a defined tab in internet explorer 7. Just need some help/pointers on the tab refresh part or if it's even possible... I don't want IE to open another tab, and another browser is not an option as the web based program is only compatible with IE. Any ideas? I've experimented with a VBS file with no luck and seeing how it's a web based program I cannot add Java Script to the page...
I know you said you tried VBScript, but it really is the most suitable solution for what you're trying to achieve. See "Hey, Scripting Guy! Blog: How Can I Tell if Any Internet Explorer Windows Are Open to a Particular Web Site?"
See the code:
For i = 0 to objShellWindows.Count - 1
Set objIE = objShellWindows.Item(i)
strURL = objIE.LocationURL
If InStr(strURL, "http://www.microsoft.com/technet/scriptcenter")Then
blnFound = True
End If
Next
Each iteration returns an instance of an open Internet Explorer window's WebBrowser Control. Instead of the blnFound = True try objIE.Refresh2().
You could frame the site, then refresh it from the outer frame with javascript on a timer. This may or may not suit your needs.
This is doable, but it's a little tricky and it requires a constraint: the tab you want to refresh has to have been opened by a Javascript call to window.open and it has to have a name. Let's call that name foo. Then you need to simply load another web page in that same browser session to execute the following Javascript:
window.open('http://other.site.url/etc', 'foo');
This means you need to both know the name of the frame and the target URL. But it's certainly doable.
Doing this from a batch file requires some scripting. In VBScript the code would be something like:
Dim browser
Set browser = CreateObject("SHDocVw.InternetExplorer")
browser.visible = True
browser.navigate("http://mysite.org/refresh.html")
Where refresh.html is the page containing the above Javascript followed by a call to window.close()
Assuming you have control over the web page too...
I'm suprised no one brought up the age old meta refresh.
Rather than do some goofy iframe/javascript magic, or some crazy IE COM object mambo, you could always write a meta refresh tag into your given a certain querystring is passed (or all the time, I don't know what your needs are)
Again, I'm not sure this suits your needs, but it is quick and pretty clean.
put this in your and it will refresh the page once every 60 seconds:
<meta http-equiv="refresh" content="60">

Categories

Resources