Cypress unable to save current URL with `as` - url

My web app generates a UUIDv4 for every new 'post', and each post has its own URL like /posts/<uuid>. I'm not able to predict what uuid gets generated, and therefore I'm unable to go back to a specific post that was created earlier during testing.
According to the docs, cy.url() returns the URL as a string. I tried saving the URL using a .as(), but it didn't work:
cy.url().as('postUrl');
// go somewhere else
cy.visit('#postUrl');
// ends up visiting `localhost:3000/#postUrl`
I saw in another SO question that I should use .then on cy.url(), but that didn't work either:
cy.url().then(url => url).as('postUrl');
// go somewhere else
cy.visit('#postUrl');
How do I save the current URL for use later?

Found the answer buried in later pages of a google search. In order to use the saved URL, use cy.get('#postUrl') and call a .then with a callback that visits that url.
cy.url().as('postUrl');
// go somewhere else
cy.get('#postUrl').then(url => {
cy.visit(url);
}

var currentUrl=''
cy.url().then(url => {
currentUrl = url;
});
cy.visit(currentUrl)

Related

Include multiple incoming SMS messages/responses with Twilio functions

I'm working on a project now within Twilio, using Twilio Functions, where I'm trying to set up SMS messaging so that if we receive an incoming keyword, we respond with a specific message, including a URL. The plan is to have multiple incoming keywords, with different responses so if someone sends an SMS to one of our numbers, depending on that key word, we respond with a basic message and a URL. I'm trying to figure out the best way to handle this within Twilio Functions.
I have this working for a single incoming keyword/response, as seen below.
if (incomingMessage.includes('testpark')) {
twiml.message('StartMyParking:\n\nTo start your parking, please click this link: https://blahblah.com');
} else if (incomingMessage.includes('bye')) {
twiml.message('Goodbye!');
} else {
twiml.message('Please check your zone/code and try again.');
}
While that works, I want to add in more incoming words, along with responses, such as an incoming message of 'testpark2' and a response of 'StartMyParking:\n\nTo start your parking, please click this link: https://blahblah2.com'.
Then I would want to include another one with 'testpark3' and a response of 'StartMyParking:\n\nTo start your parking, please click this link: https://blahblah3.com' and so on, all within the same script.
Can someone help me understand how to achieve this?
There are a lot of ways to achieve your desired outcome, but here's the most straightforward to begin with.
Instead of creating an else if statement for every possible keyword, you could define the keyword/response pairs up front using a JavaScript Map.
The keys of the Map will be your keywords, the values of the Map will be your responses:
const keywordResponseMap = new Map([
['testpark2', 'StartMyParking:\n\nTo start your parking, please click this link: https://blahblah2.com'],
['testpark3', 'StartMyParking:\n\nTo start your parking, please click this link: https://blahblah3.com'],
['testpark', 'StartMyParking:\n\nTo start your parking, please click this link: https://blahblah.com'],
]);
const keywords = Array.from(keywordResponseMap.keys());
let keyword;
if (incomingMessage.includes('bye')) {
twiml.message('Goodbye!');
}
else if (keyword = keywords.find(k => incomingMessage.includes(k))) {
const response = keywordResponseMap.get(keyword);
twiml.message(response);
} else {
twiml.message('Please check your zone/code and try again.');
}
Also note that I'm putting the bye case up front because it is more performant than looking for the keywords in the incomingMessage, thus you avoid unnecessarily doing that processing when a user says bye.
You can use find to search for any keyword that is in the incomingMessage, then you can use the keyword that you found to retrieve the response from the map.
If your response will always be the same except for the URL, you could further optimize this by only storing the URL in the map and using string interpolation like this:
const keywordUrlMap = new Map([
['testpark2', 'https://blahblah2.com'],
['testpark3', 'https://blahblah3.com'],
['testpark', 'https://blahblah.com'],
]);
const keywords = Array.from(keywordUrlMap.keys());
let keyword;
if (incomingMessage.includes('bye')) {
twiml.message('Goodbye!');
}
else if (keyword = keywords.find(k => incomingMessage.includes(k))) {
const url = keywordUrlMap.get(keyword);
twiml.message(`StartMyParking:\n\nTo start your parking, please click this link: ${url}`);
} else {
twiml.message('Please check your zone/code and try again.');
}
It is also important to note that I'm putting testpark last in the map because testpark matches to testpark2 and testpark3. If you'd put it first, it would always resolve to testpark even with a user submits testpark2 or similar values.
Also, I'm using the Map type because it guarantees the order in which the keys are returned, which is again important for the previous point.
When you have a lot more keywords and responses, you may have to start looking at a solution to store them externally like a database, and query the database by keyword to resolve the response.
Good luck, we can't wait to see what you build!

Is there a way to get the URL after a redirect in postman?

I'm working with an API, which after filling out the log in form on their website, redirects back to our website, with a unique code at the end of the URL.
Example URL after redirect:
https://www.mywebsite.com/?code=12431453154545
I have been unable to find a way of viewing this URL in Postman.
Ideally I need to be able to work with that URL to extract the code and store it as a variable.
Any help will be muchly appreciated. I've been trying this all day :( .
When you turn off following redirects in Postman settings, you will be able to inspect 3xx HTTP response which will contain Location header with the URL you want to read.
const url = require("url");
var location = pm.response.headers.get("location");
if (typeof location !== typeof undefined) {
var redirectUrl = url.parse(location, true);
query = redirectUrl.query;
if ("code" in query) {
pm.globals.set("code", query.code);
console.log(pm.globals.get("code"));
}
}
Note that this solution will not work when multiple subsequent redirects happen as you will be inspecting only the first 3xx response. You could solve this by following redirects manually and sending your own requests from Postman script as described in Postman manual.

Create URL with /#/ in path and open in safari

I use firebase dynamic links which contain an URL to our webapp.
If the dynamic link is opened, the deep link is fetched.
So far so good. As we use the /#/path pattern in our webapp to redirect a user to different sections, we have a problem now, creating such an url in our iOS application after we have to append a new parameter in the url
If this example URL is in our dynamic link
https://domain/#/main/page?utm_source=app&utm_medium=button&utm_campaign=testcampaign
i get it and have to append a parameter for autologin mechanism in our webapp.
So here is the point where i fail at two different approaches.
Getting the string from the url and appending the token parameter and value.
This approach works fine until I have to parse the urlString back to an URL object. The /#/ inside causes an error when creating a new URL object.
I try to replace /#/ with /%23/ (encoded #), but this does not work on our ngnix / webapp infrastructure.
Appending the token parameter with new URLQueryItem in URLComponents.
This approach leads to a wrong URL resulting in (token is the added parameter)
https://my-stage.bikersos.com/?token=tokrenvalue#/main/premium?utm_source=app&utm_medium=button&utm_campaign=testcampaign
I append the URL Query Item with this extension
extension URL {
func addQueryParams(newParams: [URLQueryItem]) -> URL? {
let urlComponents = NSURLComponents.init(url: self, resolvingAgainstBaseURL: false)
guard urlComponents != nil else { return nil; }
if (urlComponents?.queryItems == nil) {
urlComponents!.queryItems = []
}
urlComponents!.queryItems!.append(contentsOf: newParams)
print(urlComponents!)
return urlComponents?.url
}
}
does anybody has an idea how I could solve this problem? I personally prefer the second approach, if it is possible to append the parameters at the end
I figured it out how it has to be done with firebase and utm parameters (this link can be added as deep link in a dynamic link for firebase)
https://example.domain.com/?utm_source=newsletter&utm_medium=button&utm_campaign=testcampaign#/path1/subpath?webappparam1=1&webappparam2=asdf
This way all utm parameters are applied and the path will be available in the web application too.
You can add new query params using the iOS SDK but be aware, they are added at the utm parameters location.
If you need to add them at the end, check if there already exists an ? in the path and write your own appending at the end of the url.

Changing CurrentAccessToken in Facebook Unity SDK

I'm trying to post to a Facebook page AS the page using the Unity Facebook SDK running on iOS. As I understand, to do that, I need the pages access token with manage_pages and publish_pages. I know that I can get it from /me/accounts?fields=access_token, but how do I tell AccessToken.CurrentAccessToken to use my pages access token instead?
Right now i'm using the following:
var wwwForm = new WWWForm();
//wwwForm.AddField ("access_token", "A-T I NEED");
wwwForm.AddBinaryData("image", screenshot, "InteractiveConsole.png");
wwwForm.AddField("message", "herp derp. I did a thing! Did I do this right?");
FB.API("/PAGE-ID/photos", HttpMethod.POST, HandleResult, wwwForm);
I tried putting the access token manually, but that didn't work (so I commented it out).
With this as it is I'm getting an error, telling me that I need publish_actions, wich is not correct since I'm not trying to post as the user. If I also get publish_actions the Post goes online, but is posted to the page as the user speaking. (User is also Admin)
Any Ideas ? Thanks!
So, I filed a bug report to facebook and as it turns out: "… at this time this functionality is not supported." Wich simply means there is now way to use the Page Access Token you acquired via the FB.API within the FB.API. And they are not going to tell you abot it in the documentation.
As a workaround I simply use a UnityWebRequest like this:
IEnumerator UploadToPage(byte[] screenshot) {
var wwwForm = new WWWForm();
wwwForm.AddField("message", "herp derp. I did a thing! Did I do this right?");
wwwForm.AddBinaryData("image", screenshot, "Test.png");
string url = "https" + "://graph.facebook.com/"+ PageID + "/photos";
url += "?access_token=" + PageAccessToken;
using (UnityWebRequest www = UnityWebRequest.Post(url, wwwForm))
{
yield return www.Send();
if (www.isError)
{
Debug.Log(www.error);
}
else
{
Debug.Log("Form upload complete!");
}
}
Debug.Log(url);
}

Modify URL before loading page in firefox

I want to prefix URLs which match my patterns. When I open a new tab in Firefox and enter a matching URL the page should not be loaded normally, the URL should first be modified and then loading the page should start.
Is it possible to modify an URL through a Mozilla Firefox Addon before the page starts loading?
Browsing the HTTPS Everywhere add-on suggests the following steps:
Register an observer for the "http-on-modify-request" observer topic with nsIObserverService
Proceed if the subject of your observer notification is an instance of nsIHttpChannel and subject.URI.spec (the URL) matches your criteria
Create a new nsIStandardURL
Create a new nsIHttpChannel
Replace the old channel with the new. The code for doing this in HTTPS Everywhere is quite dense and probably much more than you need. I'd suggest starting with chrome/content/IOUtils.js.
Note that you should register a single "http-on-modify-request" observer for your entire application, which means you should put it in an XPCOM component (see HTTPS Everywhere for an example).
The following articles do not solve your problem directly, but they do contain a lot of sample code that you might find helpful:
https://developer.mozilla.org/en/Setting_HTTP_request_headers
https://developer.mozilla.org/en/XUL_School/Intercepting_Page_Loads
Thanks to Iwburk, I have been able to do this.
We can do this my overriding the nsiHttpChannel with a new one, doing this is slightly complicated but luckily the add-on https-everywhere implements this to force a https connection.
https-everywhere's source code is available here
Most of the code needed for this is in the files
IO Util.js
ChannelReplacement.js
We can work with the above files alone provided we have the basic variables like Cc,Ci set up and the function xpcom_generateQI defined.
var httpRequestObserver =
{
observe: function(subject, topic, data) {
if (topic == "http-on-modify-request") {
var httpChannel = subject.QueryInterface(Components.interfaces.nsIHttpChannel);
var requestURL = subject.URI.spec;
if(isToBeReplaced(requestURL)) {
var newURL = getURL(requestURL);
ChannelReplacement.runWhenPending(subject, function() {
var cr = new ChannelReplacement(subject, ch);
cr.replace(true,null);
cr.open();
});
}
}
},
get observerService() {
return Components.classes["#mozilla.org/observer-service;1"]
.getService(Components.interfaces.nsIObserverService);
},
register: function() {
this.observerService.addObserver(this, "http-on-modify-request", false);
},
unregister: function() {
this.observerService.removeObserver(this, "http-on-modify-request");
}
};
httpRequestObserver.register();
The code will replace the request not redirect.
While I have tested the above code well enough, I am not sure about its implementation. As far I can make out, it copies all the attributes of the requested channel and sets them to the channel to be overridden. After which somehow the output requested by original request is supplied using the new channel.
P.S. I had seen a SO post in which this approach was suggested.
You could listen for the page load event or maybe the DOMContentLoaded event instead. Or you can make an nsIURIContentListener but that's probably more complicated.
Is it possible to modify an URL through a Mozilla Firefox Addon before the page starts loading?
YES it is possible.
Use page-mod of the Addon-SDK by setting contentScriptWhen: "start"
Then after completely preventing the document from getting parsed you can either
fetch a different document from the same domain and inject it in the page.
after some document.URL processing do a location.replace() call
Here is an example of doing 1. https://stackoverflow.com/a/36097573/6085033

Resources