Gatsby/React - Get Referring Url - javascript

Building a jobs board. Need to know if the user clicked on our link from monster.com, jobs.com, foobar.com, etc. This needs to happen in the code, as I need to send it to an API.
What is the best way to accomplish this?
I tried searching around, but can only find articles on internal routing, e.g.:
How to get previous url in react gatsby
If I need to do this in plain Javascript (not available "out-of-the-box"), please point me in the right direction there too. Not even sure what to google for this other than "UTM parameters". We are using Google Analytics and the marketing team is including utm params in the links, if that helps.

In gatsby each page component has a location prop with some useful info. So you could do something like:
import React from "react"
const IndexPage = ({ location }) => {
console.log(location.search.split("?")[1].split("&"))
return (
<div>
My homepage
</div>
)
}
export default IndexPage
So visiting https://myapp.com/?campaign=foo&id=bar would log ["campaign=foo", "id=bar"]. With that info, you could decide how and when to communicate with your APIs to log the relevant info.

This question was very vague, because I did not understand what I was asking when I posted it. There is two scenarios here that should help you get started. If you have specific questions, follow up - I will try to help.
Scenario 1 (will most likely NOT work, but here for completeness): You are getting referrals from websites you are not at all associated with. For example, you run mycoolsite.com and someone at someforum.com linked to you. The ONLY way you are going to be able to know this without anything additional is if someforum.com sends something called a Referer Request Header. Many popular sites do not.
Scenario 2: Your marketing team pays someone to link to you for a specific promotion. E.g., your marketing team tells someforum.com to link mycoolsite.com for money or as a favor. In this case, they can request that scenario 1 be followed OR, more likely, they can include something called utm params, e.g. when they send the link it's not mycoolsite.com?utm_campaign=monster&utm_source=monsterjobs
When the request comes in to your site, you can then pull these utm params out, to identify which campaign is working.
The code for that looks something like this:
function buildUtmInfoString(currentUrlString) {
const url = new URL(currentUrlString);
let referrerString = '';
utmParamNames.forEach(paramName => {
const paramValue = url.searchParams.get(paramName.standard);
if(!paramValue) {
return;
}
const paramString = `${paramName.colloquial}: ${paramValue}, `;
referrerString += paramString;
});
referrerString = referrerString.substring(0, referrerString.length-2);
return referrerString;
}
Note that you might need to look up utm param standard names, they are supported by Google Analytics out of the box, if your company uses that, but you can use them without GA.
const standardUtmParamNames = {
SOURCE: 'utm_source',
MEDIUM: 'utm_medium',
CAMPAIGN: 'utm_campaign',
TERM: 'utm_term',
CONTENT: 'utm_content'
};
const utmParamNames = [
{
standard: standardUtmParamNames.SOURCE,
colloquial: 'Source'
},
{
standard: standardUtmParamNames.MEDIUM,
colloquial: 'Medium'
},
{
standard: standardUtmParamNames.CAMPAIGN,
colloquial: 'Campaign'
},
{
standard: standardUtmParamNames.TERM,
colloquial: 'Term'
},
{
standard: standardUtmParamNames.CONTENT,
colloquial: 'Content'
}
];
export default utmParamNames;
Note that there are also hacks to accomplish this, but they are not reliable and can be seen as abuse of your user's privacy, so they aren't viable business solutions and I don't recommend wasting time on them.

Related

Error with AWS SDK-JS API when Retrieving Seller Partner Product Catalog Inventory

I need to retrieve the product catalog of my seller partner on Amazon. Although the API refers to this as "Inventory," I couldn't find this term in the SDK documentation. I assume that the "Catalog" namespace is the equivalent.
Update:
My custom application requires a list of the following product values:
ASINs
UPCs
SKUs
FNSKUs
I have read the documentation and found an API that returns what I need, which can be found here:
https://developer-docs.amazon.com/sp-api/docs/fba-inventory-api-v1-use-case-guide
According to the documentation, I need to create a signature in order to use the API. However, it is noted that if I use the AWS SDK, I do not need to calculate the signature myself. Therefore, I understand that the best practice is to use the AWS SDK.
I have the necessary IAM role permissions and the SP-API app has been published. I am currently attempting to use the AWS SDK.
I have made some changes based on recommendations, but I am not completely sure what else I need to do. Here is my current code:
```
export const /*bundle */ start = async () => {
const client = new MarketplaceCatalogClient({
region: REGION,
credentials: {
accessKeyId: ACCESS_KEY_ID,
secretAccessKey: ACCESS_SECRET_KEY,
},
});
const params = {
/** input parameters */
};
const answer = await client.send(
new ListEntitiesCommand({ Catalog: "AWSMarketplace", EntityType: "ContainerProduct" })
);
console.log(100, answer);
return answer;
};
```
I got the next answer with "AmiProduct" or "ContainerProduct":
{
'$metadata': {
httpStatusCode: 200,
requestId: '91fc5fed-6cdc-42d6-97ec-1ed3cc9d5796',
extendedRequestId: undefined,
cfId: undefined,
attempts: 1,
totalRetryDelay: 0
},
EntitySummaryList: []
}
I'm having difficulty understanding how to correctly implement this. Any guidance would be greatly appreciated.
The docs should be better. I spent a good 15 mins on the docs at https://docs.aws.amazon.com/marketplace-catalog/latest/api-reference/welcome.html and failed to find a full list of valid EntityType values.
Some EntityType values are documented here: https://docs.aws.amazon.com/marketplace-catalog/latest/api-reference/seller-products.html
AmiProduct
ContainerProduct
It looks like these types correspond to the product types in the index of the seller guide here -> https://docs.aws.amazon.com/marketplace/latest/userguide/machine-learning-products.html. It's not clear what the other valid values are.
Some other EntityType values are documented here: https://docs.aws.amazon.com/marketplace-catalog/latest/api-reference/private-marketplace.html
Experience
Procurement Policy
It looks the way to go for now is to scrounge these valid values from examples in the docs https://docs.aws.amazon.com/marketplace-catalog/latest/api-reference/welcome.html. Not the best developer experience :grimace:
Assuming you are a seller, that you have registered successfully with your AWS account. You can then use Marketplace APIs.
To use them, you have to create an IAM role or a user with policies to grant access to invoke the selected APIs like listEntities, describeEntity, etc.
Here I again assume you have the Cognito authorized credentials if using AWS SDK.
Now to view the list of products successfully published, you use listEntites command.
You can only view AMI or Containter product types. Read here.
It uses minimum two required parameters Catalog and EntityType. The former has a fixed value AWSMarketplace, and latter can have a value either AmiProduct or ContainerProduct.
To get a detailed information about a specific product, you use describeEntity command. It takes minimum 2 required parameters Catalog and EntityID.
The former again has a fixed value AWSMarketplace. For latter, you'll obtain it from the listEntites response.

Let Strapi CMS create pages based on html template file

So probably my explanation is awful, but i really don’t know how to express my problem or what to search for.
I got a site (www.example.com/blog.html) showing all blog post entries created in a headless cms (Strapi). The site receives the posts by making an url request and parsing the resulting JSON data. This data also contains an unique url slug for each post serving as an identifier.
I want to create one page for each blog post created in the headless cms based on a „template“ html.
What I tried is passing the urlslug as a url parameter (www.example.com/blog/article.html?id=*URLSLUG*) and then using this url parameter to fetch the corresponding post data from the cms. I followed this guide: https://strapi.io/blog/build-an-editorial-website-with-vanilla-java-script-and-strapi
It works, but I don’t want to rely on url parameters for seo reasons. Instead I want something like www.example.com/blog/*URLSLUG*. In other words: I want to have one page for each blog post entry in my headless cms based on a „template“ html.
Any suggestions?
Code can be added if necessary
well there is few options here:
The first one is most reliable, and easy but seems not that fancy as you want:
https://market.strapi.io/plugins/strapi-plugin-slugify
The main reason to use this solution is that it handles slug creation when you create post via REST api. The uuid field needs extra work when post created not from admin panel.
So second option is do it yourself style:
/api/article/controller/article.js
module.exports = createCoreController('api::article.article', ({strapi}) => ({
findOne(ctx){
const { slug } = ctx.params;
return strapi.db.query('api::article.article').findOne({where: {slug});
}
});
then in the routes create routes.js file
/api/article/routes/routes.js
module.exports = {
routes: [
{
method: 'GET',
path: '/articles/:slug'
handler: 'article.findOne'
}
]
}
then if you want to create articles for outside of admin, create lifecycles.js in
/api/article/content-types/article/lifecycles.js
module.exports = {
async beforeCreate(event) {
// here you have to do something like
let slug = slugify(event.result.name);
let isNotFree = await strapi.db.query("api::article.article").findOne({where: {slug}});
if (Boolean(!isNotFree)) // < not sure prolly need an empty object check
for (let i = 1; i < 9999 ; i++) {
slug = `${slug}-${i}`;
isNotFree = await strapi.db.query("api::article.article").findOne({where: {slug}});
if (Boolean(!isNotFree))
break;
}
event.result.slug = slug
}
}
pleas note the lifecycle code is just a first thing came to my mind, should be tested and optimized prolly
the implementation gives you the findOne controller, you gonna need to do it for each other update, delete, etc...

Expo notification click to action

I can't seem to find a solution when I get a push notification and click on it redirects me to a screen, chat, etc. link to push notification.
I would also like to add a square image to the side and could not find an answer.
The push notifications are sent from a NodeJS server I looked at the docs and search the internet and I did not find anything of interest.
https://docs.expo.dev/versions/latest/sdk/notifications/#managing-notification-categories-interactive-notifications
https://github.com/expo/expo-server-sdk-node
Thank you in advance for your answers ❤️
I'm not quite sure about the square image, but in order to handle redirects you can look at this documentation from expo: https://docs.expo.dev/push-notifications/receiving-notifications/.
You can then pass the data you need for your redirect (i.e. notification_type, relevant id etc) via the data property on your message (this will need to be done wherever the message is created, which from your question is from the node api):
messages.push({
to: pushToken,
body: 'This is a test notification',
data: { notification_type: 'something', id: 'something_else' },
});
It is then up to you to decide how to handle that message based on the extra data you have provided.
For example, taking the code provided in the link above as an example, you could have a handle function as follows:
_handleNotification = response => {
const data = response.notification.request.content;
if (data.type === "new_message") {
// navigate to MessageScreen with data.id as param
} else {
// do something else based on the type or...
}
};

About badly documented patreon-js

I don't understand this documentation, I tried so hard to do the mentioned info below but I am not quite sure what "jsonApiURL" is. Can someone tell me how to properly achieve the goal in the quote.
Response Format
You can request specific related resources and or resource attributes
that you want returned by our API, as per the JSON:API specification.
The lists of valid includes and fields arguments are provided in
patreon/schemas. For instance, if you wanted to request the total
amount a patron has ever paid to your campaign, which is not included
by default, you could do:
const patreonAPIClient = patreonAPI(access_token)
const url = jsonApiURL(`/current_user`, {
fields: {
pledge: [...pledge_schema.default_attributes, pledge_schema.attributes.total_historical_amount_cents]
}
})
patreonAPIClient(url, callback)
More info below
https://github.com/Patreon/patreon-js

Firefox - Intercept/Modify post data when some variable match some pattern

I would like to know if it is possible to intercept and modify a post data when the url and some of the variables meet some pattern.
for example:
let the login url be: http://www.someonlineprofiles.com
let the post data be:
email: "myemail#gmail.com"
pass: "mypass"
theme: "skyblue"
I would like that if:
url = "http://www.someonlineprofiles.com/ajax/login_action_url" and
email = "myemail#gmail.com"
then theme value be unconditionally changed to: "hotdesert"
Is it possible to create a Firefox add-on for that?, are add-ons powerful enough for that?
I found this link:
modify the post data of a request in firefox extension
Thanks in advance!
[ADDED INFORMATION]
I don't know if it is interesting to know the version of my Firefox: 35.0.1
Your question borders on being too broad, so I will give only an overview on how to do this, but not a copy-paste-ready solution, which would take a while to create, and would also deny you a learning experience.
Observers
First of all, it is possible for add-ons to observe and manipulate HTTP(S) requests before the browser sends the request, you just need to implement and register what is called a http observer.
const {classes: Cc, instances: Ci, utils: Cu} = Components;
Cu.import("resource://gre/modules/Services.jsm"); // for Services
var httpRequestObserver = {
observe: function(channel, topic, data) {
if (topic != "http-on-modify-request") {
return;
}
if (!(channel instanceof Ci.nsIHttpChannel)) {
return; // Not actually a http channel
}
// See nsIChannel, nsIHttpChannel and nsIURI/nsIURL
if (channel.URI.host != "www.someonlineprofiles.com") {
return;
}
doSomething(channel);
},
register: function() {
Services.obs.addObserver(this, "http-on-modify-request", false);
},
unregister: function() {
Services.obs.removeObserver(this, "http-on-modify-request");
}
};
httpObserver.register();
// When your add-on is shut down, don't forget to call httpObserver.unregister();
Do only register the http observer once in your add-on:
If you're using the SDK, then put it into main.js or a dedicated module. You'll also need to rewrite the code a bit and replace the const .. = Components line with a require("chrome").
If you're writing a XUL overlay add-on, put it into a code module.
Rewriting post data
We still need to implement doSomething() and actually rewrite the post data. An http channel usually implements the nsIUploadStream interface, and the upload stream is where the current post data is, if any. It also has a setUploadStream() method, which you can use to replace the upload stream entirely.
function doSomething(channel) {
if (!(channel instanceof Ci.nsIUploadStream)) {
return;
}
// construct new post data
channel.setUploadStream(newStream);
}
Constructing the new post data would be a matter of your actual requirements. I provided a working example in another answer on how you could do it.
If you need to fetch some data from the old upload stream, you'll need to decode the existing channel.uploadStream as multipart/form-data yourself. I suggest you check TamperData and similar add-ons on how they do things there.

Categories