We are using selenium for automation. We need to launch 2 URLs simultaneously.
I am using driver.get to load first URL , which has in-built synchronization for page load. To load second window , I am using code below -
String jscript="window.open('"+strURL+"')";
js.executeScript(jscript);
It works fine on chrome but on Edge , page takes time to load and when I try to do switchwindow to another window using title , it does not find window with that title.
if I add wait , then window loads and switchwindow works perfectly.
I don't want to use hardcoded wait .How I can check whether 2nd window is loaded completly?
I tried below , but it gives permission error on Edge-
String jscript="var win=window.open('"+strURL+"');win.onload=function(){}";
js.executeScript(jscript);
Try this to check whether page is loaded or not properly.
wait.until( new Predicate<WebDriver>() {
public boolean apply(WebDriver driver) {
return ((JavascriptExecutor)driver).executeScript("return document.readyState").equals("complete");
}
}
);
Hope it will help.
Related
I am trying to inject some javascript into my web view when it is navigated to a product page URL. The website doesn't reload when navigating to different pages, so to my understanding that means it is using Ajax.
The problem is I need the page to be fully loaded because the purpose of the javascript I am using is to automatically select the size drop down.
I tried to use the navigation delegate but since it's not reloading between pages it only gets called when the web view is first loaded.
What I have done is setup and observer by
webView.addObserver(self, forKeyPath: "URL", options: .new, context: nil)
and check if the current URL is the URL I want to inject the javascript on by
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "URL" {
guard var currentURL = webView.url?.absoluteString else { return }
if currentURL.lowercased().range(of: "products") != nil {
webView.evaluateJavaScript("document.getElementById('size-options').selectedIndex = 1")
}
}
}
The problem with this is it gets called right when the URL changes but not when the page finishes loading. I have got it to successfully work by adding a delay but that isn't a good solution because if the page doesn't load in time it won't work. Is there any way to know when a page like this finishes loading all its elements? The website I am working with is http://www.supremenewyork.com/mobile/#categories mobile site.
I have written a website that uses bankid authentication, I don't know how common this is outside of sweden, but basically it is either an app in the mobile phone, or a local software in windows. to launch the application in windows a redirect needs to be made that looks like this:
if (startLocalApp)
{
Response.Redirect("bankid:///?autostarttoken=" + AuthResp.AuthenticateResponse1.AutoStartToken + "&redirect=" + Request.Url.AbsoluteUri);
}
the problem with this though is that the redirect of the software does not work the way I need it to work since the redirect it does opens a new tab with the web page I need to get back to in a new tab, and the session variable is all messed up. so what I need to do is the opposite, launch the app in a new tab, and let it close the tab when it's done, since I have all references needed before I've launched the app it does not need to be executed in the same browser window even.
so how to make the redirect in another tab, and is it possible to keep executing code after the redirect? if not, I need to make a post back to continue execution of the code-behind.
edit:
I've tried one solution, it feels like I'm getting closer but I'm not quite there yet.
front-end:
<script type="text/javascript">
function StartBankIdApp(){
var _url = 'bankid:///?autostarttoken=<%= (AuthResp == null || AuthResp.AuthenticateResponse1 == null) ? "null" : AuthResp.AuthenticateResponse1.AutoStartToken %>&redirect=null';
var $irWin = window.open(_url, '_blank');
if ($irWin != null) {
$irWin.close();
}
}
</script>
code-behind:
if (startLocalApp)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), StartBankIdApp", "StartBankIdApp()", true);
}
the app is not launched, i.e the window it should open does not open.
did I do something wrong?
I think you are trying to use "URL scheme" to launch an app. And that you want that the app should be triggered in a new tab (or window).
This can be achieved through javascript. To open any link in new tab we can use window.open and set target attribute as _blank. Here is a sample code
var _url = 'app:MyApp?queryString=somestring';
var $irWin = window.open(_url, '_blank');
if ($irWin != null) {
$irWin.close();
}
What I've done here is that after launching the app I've closed the new tab (or window).
The javaScript code would continue to run (that is it will not wait for the app to complete the process).
I am looking for a way to confirm the image has actually loaded. Maybe JavaScript is an option? I am using right now WebdriverWait to simply force the wait on all images, then the actual src, then I finally run my tests after...
wait = WebDriverWait(driver, 10)
...
albums = wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, ".albums .album img")))
albumslength = len(albums)-1
while albumslength > 0:
wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, ('.album:nth-child('+str(albumslength)+') img[src*="album-foo"]'))))
albumslength -= 1
...
This will at some point confirm "album-foo" exists in the <img src="http://www.album-foo/images/blah.jpg" of each album in albums. But it does not confirm that the image completed loading into view. I have searched high and low, anyone have a solution?
I am testing on Chrome and Firefox, so no phantom or IE restrictions, if the ideas grow into including JavaScript or related ideas that might have environment restrictions.
I am not that experienced with selenium, though I will give this a try.
If you want to check whether an image is loaded, I'd say use a boolean. Set the original value of this boolean let's say 'loaded' to false.
Then just call something like this, making sure it returns true the moment the image has loaded.
Boolean loaded = false;
WebDriver driver = new AnyDriverYouWant();
JavascriptExecutor js;
if (driver instanceof JavascriptExecutor) {
js = (JavascriptExecutor)driver;
}
loaded = (Boolean)js.executeScript("image.onload(function() { return true; });");
I try to write a Google Chrome extension that simply opens a new tab when I click left-right in a short interval. The JavaScript is no problem but I implemented this as a "content_scripts" script.
In some other threads I read that I can't access the chrome.* APIs from content_scripts (except the chrome.extension API).
Even if it's not necessary to access the chrome.tabs API to open a new window (window.open should do the job) it seems I need it though for opening a new tab with the new tab page which obviously isn't possible via window.open.
So I can't really figure out what is the best way to do that. I could use a background page which I could call from the content_script but I think there should be a much more simple way to do that, I just don't get it.
Anyone have an idea?
I think your content script will have to send a message to your background page to invoke chrome.tabs.create - content scripts cannot use the chrome api, nor can they directly communicate with the background page.
Here's a reference about message passing inside Chrome extensions for further detail, but here's the example code ( modified from the example in said reference )
// in background
chrome.extension.onMessage.addListener(
function(request, sender, sendResponse) {
switch ( request.action) {
case 'newTab' : {
//note: passing an empty object opens a new blank tab,
//but an object must be passed
chrome.tabs.create({/*options*/});
// run callback / send response
} break;
}
return true; //required if you want your callback to run, IIRC
});
// in content script:
chrome.extension.sendMessage({action: "newTab"}, function(response) {
//optional callback code here.
});
simple and easy
document.body.onclick = function openNewWindow( ) {
window.location.href = 'javascript:void window.open( "chrome://newtab" )';
}
manifest:
,"permissions":[
"http://*/*"
,"https://*/*"
]
,"manifest_version": 2
,"content_scripts":[{
"matches":[
"http://*/*"
,"https://*/*"
]
,"js":[
"js/openWindow.js"
]
}]
alright i miss understanding the question... modified
I want to create an extension that redirects the user to another website if he clicks on the extension button. So far I have only seen extensions which create a new tab for each click.
Is it possible to redirect the user to another website using the active tab?
I tried something like this:
chrome.browserAction.onClicked.addListener(function(tab) {
var url = "https://www.mipanga.com/Content/Submit?url="
+ encodeURIComponent(tab.url)
+ "&title=" + encodeURIComponent(tab.title);
document.location.href = url; // <-- this does not work
});
Attention: If you develop cross-browser extensions (I hope you do!), I recommend that you use chrome.tabs.query(). Please see Jean-Marc Amon's answer for more information. This answer still works in both Firefox and Chrome, but query() is more commonly used, has more options, and works in background pages and popup views.
From the chrome.tabs API, you can use getCurrent(), query(), or update().
Right now, I prefer update() as this allows you to update the current tab without needing to do much else.
NB: You cannot use update() from content scripts.
If updating the url from a content script is required then you should look to use query instead. Jean-Marc Amon's answer provides a wonderful example of how to get the active tab in this case (don't forget to upvote him!).
update()
let myNewUrl = `https://www.mipanga.com/Content/Submit?url=${encodeURIComponent(tab.url)}&title=${encodeURIComponent(tab.title)}`;
chrome.tabs.update(undefined, { url: myNewUrl });
Here, we have set the first argument of update to undefined. This is the tab id that you're wanting to update. If it's undefined then Chrome will update the current tab in the current window.
Please see Domino's answer for more information on update and also note that undefined is not needed. Again, please don't forget to upvote their answer as wellif you find it useful.
getCurrent()
getCurrent also cannot be called from a non-tab context (eg a background page or popup view).
Once you have the current tab, simply pass update().
chrome.tabs.getCurrent(function (tab) {
//Your code below...
let myNewUrl = `https://www.mipanga.com/Content/Submit?url=${encodeURIComponent(tab.url)}&title=${encodeURIComponent(tab.title)}`;
//Update the url here.
chrome.tabs.update(tab.id, { url: myNewUrl });
});
NB: In order to use this this functionality, you must ensure that you have the tabs permission enabled in your manifest.json file:
"permissions": [
"tabs"
],
You can use chrome.tabs.query too
chrome.tabs.query({currentWindow: true, active: true}, function (tab) {
chrome.tabs.update(tab.id, {url: your_new_url});
});
The chrome.tabs.update method will automatically run on the current active tab if no tab id is passed.
This has the added advantage of not requiring the tabs permission. Extensions with this permission warn the user that they can read the browsing history, so you should avoid asking for it if you don't need to.
Changing the current tab's URL is as simple as writing this:
chrome.tabs.update(undefined, {url: 'http://example.com'});
Or as mentionned by farwayer in the comments, you don't need to put two arguments at all.
chrome.tabs.update({url: 'http://example.com'});
The answers given here no longer work: the Chrome Tabs API can no longer be used by content scripts, only by service workers and extension pages.
Instead, you can send a message to a service worker to get it to update the location of the current tab: see https://stackoverflow.com/a/62461987.
See this for a simple working example.