Sure, I can help you create a JavaScript function that uses the Google Ads API v17 to add a negative keyword to a specified campaign. Below is a code snippet demonstrating how to achieve this using Node.js and the Google Ads API client library.
First, ensure you've installed the necessary client library for Google Ads API:
npm install @google-ads/api
Here is the function:
const { GoogleAdsClient, enums } = require('@google-ads/api');
async function addNegativeKeywordToCampaign(client, customerId, campaignId, keywordText) {
const googleAdsClient = new GoogleAdsClient({
// Assuming `client` is an authenticated client.
client,
});
// Define the negative keyword criterion object
const keywordCriterion = {
keyword: {
text: keywordText,
match_type: enums.KeywordMatchType.BROAD,
},
negative: true,
};
// Create the campaign criterion resource name
const campaignCriterion = {
campaign: `customers/${customerId}/campaigns/${campaignId}`,
criterion_id: generateCriterionId(), // This should be unique
negative: true,
keyword: keywordCriterion.keyword,
};
// Create the campaign criterion operation
const campaignCriterionOperation = {
create: campaignCriterion,
};
try {
// Send the operation to the API
const response = await googleAdsClient.mutateCampaignCriteria({
customer_id: customerId,
operations: [campaignCriterionOperation],
});
console.log(`Added negative keyword ${keywordText} to campaign ${campaignId}`);
return response;
} catch (error) {
console.error('An error occurred:', error);
}
}
// Utility function to generate a unique criterion ID
function generateCriterionId() {
return Math.floor(Math.random() * 1e9).toString();
}
// Example usage
const client = {}; // You should replace this with your authenticated client
const customerId = 'YOUR_CUSTOMER_ID';
const campaignId = 'YOUR_CAMPAIGN_ID';
const keywordText = 'YOUR_NEGATIVE_KEYWORD';
addNegativeKeywordToCampaign(client, customerId, campaignId, keywordText);
Notes:
- Client Authentication: Ensure that
client is an authenticated instance with proper credentials setup.
- Unique Criterion ID: Generating a unique criterion ID ensures that you're not duplicating any existing criteria.
- Error Handling: Proper error handling is crucial in a production environment. The provided example logs the error message for simplicity.
Pre-requisites:
- Properly initialized and authenticated Google Ads API client.
- Required OAuth2 credentials setup and permissions granted.
Make sure to replace placeholders like YOUR_CUSTOMER_ID, YOUR_CAMPAIGN_ID, and YOUR_NEGATIVE_KEYWORD with actual values.
This function uses the mutateCampaignCriteria method to add a negative keyword to an existing campaign with a broad match type.