How to delete cookies through a script?

Updated On Aug 8, 2014 by

Cookies are those small files on your computer that store information between sessions or between two login attempts. There are valid reasons where you might need to delete cookies stored on your computer through scripting.Delete cookies

Now, how can we delete cookies through VB Scripting in QTP? This one is a very often repeated question on the testing tools forums. I will first provide a hint here.

  1. You need to write a custom function to do this. IMHO there is no direct way available.
  2. Write a shell script to reach to the cookies file residing in your corresponding folder.
  3. Delete all the files inside that folder.

Please post your script in the comments below. If I don’t get an answer by tomorrow, I will update the post with my script.

Answer: Use WebUtil.DeleteCookies whenever you want to delete cookies from IE.

Update: As pointed by Paul on LearnQTP feedback forum, we now have some other methods as well to delete cookies/browser cache.

To clear Cache from the browser

Browser("Page Title").ClearCache

To delete Cookies from the browser

Browser("Google.com:").DeleteCookies "Google"

The above code will delete cookies for ALL Google domains like google.net, google.com, google.in.  If you wish to remove cookies for a specific domain use the corresponding Top Level Domain

Browser("Google.com:").DeleteCookies "Google.in"

There are interesting methods posted in the comments section below, don’t forget to check those.

Welcome new readers: Download the Free eBook!

Ankur JainI am Ankur Jain, the owner of LearnQTP and founder of a software organization. This site is run, maintained and updated by me and my team. Feel free to take a look around, you may want to start with What is QTP? 

You can connect with me on my Google+ page. 

Please enter your first name and email address below to instantly download the eBook on Optimizing QTP Scripts. In future, we will make sure you get new tips & tricks on QTP delivered direct to your email box.



Share This:

35 Comments

  1. Ganesh

    The below code will delete cookies and offline content from IE, clear ‘temp’ folder and recycle bin. We can use it as ‘.vbs’ file before starting execution or regression.

    on error resume next

    ‘#————————————————————————–
    ‘# Delete Cookies and offline content in IE
    ‘#————————————————————————–

    Set WshShell = CreateObject(“shell.application”)
    WshShell.ControlPanelItem “inetcpl.cpl”

    Set objShell = CreateObject(“Wscript.Shell”)
    Do Until Success = True
    Success = objShell.AppActivate(“Internet Properties”)
    Wscript.sleep 100
    Loop
    objShell.Sendkeys “%i”
    Wscript.sleep 100
    objShell.Sendkeys “{ENTER}”
    Wscript.sleep 100
    objShell.Sendkeys “%f”
    Wscript.sleep 100
    objShell.Sendkeys “%d”
    Wscript.sleep 100
    objShell.Sendkeys “{ENTER}”
    Wscript.sleep 100
    objShell.Sendkeys “{ENTER}”

    Set WshShell = Nothing
    set objShell = Nothing

    ‘#————————————————————————–
    ‘# Delete everything in the Temp Folder
    ‘#————————————————————————–

    Set objFSO = CreateObject(“Scripting.FileSystemObject”)
    Set objTemp = objFSO.GetSpecialFolder(2)
    Set subFiles = objTemp.files
    Set subFolder = objTemp.SubFolders

    For Each sFile in subFiles

    objFSO.DeleteFile sFile,True
    Next

    For Each sFolder in subFolder

    objFSO.DeleteFolder sFolder,True
    Next

    Set objFSO = Nothing
    Set objTemp = Nothing
    Set subFiles = Nothing
    Set subFolder = Nothing

    ‘#————————————————————————–
    ‘# Delete everything in the Recycle Bin
    ‘#————————————————————————–

    Const RECYCLE_BIN = &Ha&

    Set objShell = CreateObject(“Shell.Application”)
    Set objFolder = objShell.Namespace(RECYCLE_BIN)
    Set objFSO = CreateObject(“Scripting.FileSystemObject”)
    Set colItems = objFolder.Items

    For Each objItem in colItems
    If (objItem.Type = “File folder”) Then
    objFSO.DeleteFolder(objItem.Path)
    Else
    objFSO.DeleteFile(objItem.Path)
    End If
    Next

    Set objShell = Nothing
    Set objFolder = Nothing
    Set objFSO = Nothing
    Set colItems = Nothing

  2. gola

    Browser(“Browser”).WinToolbar(“ToolbarWindow32″).Press “&Tools”
    Browser(“Browser”).WinToolbar(“ToolbarWindow32″).Press “&Tools”
    Browser(“Browser”).WinMenu(“ContextMenu”).Select “Delete Browsing History…”
    Browser(“Browser”).Dialog(“Delete Browsing History”).WinButton(“Delete cookies”).Click
    Browser(“Browser”).Dialog(“Delete Browsing History”).Dialog(“Delete Cookies”).WinButton(“Yes”).Click
    Browser(“Browser”).Dialog(“Delete Browsing History”).WinButton(“Close”).Click

  3. RAVI

    below are the constants for special folders in windows:

    &H1& Internet Explorer

    &H2& Programs

    &H3& Control Panel

    &H4& Printers and Faxes

    &H5& My Documents

    &H6& Favorites

    &H7& Startup

    &H8& My Recent Documents

    &H9& SendTo

    &Ha& Recycle Bin

    &Hb& Start Menu

    &Hd& My Music

    &He& My Videos

    &H10& Desktop

    &H11& My Computer

    &H12& My Network Places

    &H13& NetHood

    &H14& Fonts

    &H15& Templates

    &H16& All Users Start Menu

    &H17& All Users Programs

    &H18& All Users Startup

    &H19& All Users Desktop

    &H1a& Application Data

    &H1b& PrintHood

    &H1c& Local Settings\Application Data

    &H19& All Users Favorites

    &H20& Local Settings\ Temporary Internet Files

    &H21& Cookies

    &H22& Local Settings\History

    &H23& All Users Application Data

    &H24& Windows

    &H25& System32

    &H26& Program Files

    &H27& My Pictures

    &H28& User Profile

    &H2b& Common Files

    &H2e& All Users Templates

    &H2f& Administrative Tools

    &H31& Network Connections

  4. WebUtil.deletecookies -> It will delete the entire cookies session which will present in your system.

    WebUtil.deletecookie –> This code will delete the cookies related to that time available session.

  5. jerico

    hi amuthu,

    if u wanna get ABC.xml…..y cant u use Relative path

    instead of Absolute path?

    tht makes ur wrk ease(may be
    )

  6. fola

    I came up with something clever. Basically, I wrote a javascript bookmarklet, then get QTP to navigate to the bookmarklet. See code below – you will need to modify it for your cookies.

    ‘This function Deletes all the BBC cookies on the browser
    Function deleteCookies(targetBrowser)

    ‘Javascript function that deletes the bbc cookies from the browser
    jsString = “javascript:function delCookie() {var thecookie = document.cookie.split” & “(“”;””);”
    jsString = jsString & ” for (var i = 0;i < thecookie.length;i++) {cpath = (thecookie[i].search"
    jsString = jsString & "(""BBCiPlayer"") == -1) ? ""/"" : ""/iplayer""; document.cookie = thecookie[i] + "
    jsString = jsString & """; expires=Thu, 01 Jan 1970 00:00:00 GMT; domain=.bbc.co.uk; "
    jsString = jsString & "path="" + cpath; }} delCookie();"

    Browser(targetBrowser).Navigate(jsString)

    End Function

  7. MS

    hey.

    i want to know is there any specific code to delete cookies from FF . does Webutil.deletecookies delete the cookies for IE or FF ??

    thanks and Regards
    MS

  8. Neeraj Jain

    Hi Ankur,

    Could you please let me know the script for clicking the top row in Google Search results.

    I was able to write the script as follows:

    SystemUtil.Run “iexplore.exe”, “www.google.com”
    Browser(“title:=Google – Windows Internet Explorer”).Page(“title:=Google”).WebTable(“name:=q”).WebEdit(“name:=q”).Set “Testing Concepts”
    wait(5)
    Browser(“title:=Google – Windows Internet Explorer”).Page(“title:=Google”).WebTable(“name:=q”).WebButton(“name:=Google Search”).click

    What would be the code for getting QTP to click on the first(top) link in the results that are returned by the search?

    I would appreciate it if you could help me with this script.

    Thanks,
    Neeraj

  9. pandu

    I dont want to write script in the qtp.
    How to access data from excel sheet and do operations on the application.
    For that one i need functions.
    we can use the property values in the excel sheet.
    can u plz help me

  10. preeti

    WebUtil.deletecookies is the direct method available in QTP to delete the cookies

  11. Hackoo

    ‘This VBScript Made by Hackoo
    ‘it Works so fine for me :) I and i hope that could help ‘you !
    set WshShell = CreateObject(“WScript.Shell”)
    user= WshShell.ExpandEnvironmentStrings(“%userprofile%”)
    Set fso = CreateObject(“Scripting.FileSystemObject”)

    file_path = user & “Cookies”
    WScript.echo(file_path)
    Set folder = fso.getFolder(file_path)

    For Each Fichier in folder.Files
    If UCase(FSO.GetExtensionName(Fichier.Path)) = “TXT” Then
    fso.DeleteFile(Fichier)
    end if
    Next
    WScript.echo(“All Cookies are deleted succefuly !”)

  12. Virender Singh

    To delete cookies you can write a one line code.

    webutil.deletecookies

    webutil.deletecookie

    First one deletes all the cookies. Second one deletes cookies specific to the session

    Virender Singh
    sudhir0101@gmail.com

  13. Vaishali

    What is the correct script from these number of answers?

  14. Aishwarya

    Function clearCookies()

    on error Resume Next

    Const COOKIES = 33 ‘&H21&

    Set objShell = CreateObject(“Shell.Application”)
    Set objFolder = objShell.Namespace(COOKIES)
    Set objFolderItem = objFolder.Self
    strPath = objFolderItem.Path & “\*.txt”

    Set objFSO = CreateObject(“Scripting.FileSystemObject”)
    objFSO.DeleteFile(strPath)

    clearCookies = True
    If Err.Number 0 Then
    err.Clear
    msgbox(“Couldn’t clear IE cookies…”)
    clearCookies = False
    End If

    End Function

  15. Amuthu

    Hi,
    Whether is it possible to copy a specific file from a folder whose foldername gets often changed while the Test runs. The file name is constant, while the folder name containing the file gets changed. { Ex:- Filename – ABC.xml, location of the file – “C:\programfile\Test\temp*2009070310109*\Runtime\ABC.xml”. The folder temp2009070310109 value often gets changed while the Test runs, and only the first few characters are constant. My Target is to copy the ABC.xml. May i know is it possible?, if so can you please send me the Code and syntax.}
    Thanks in Advance.

  16. shakti srivastava

    how can i block or allow all cookies in ie6/7 (privacy settings) through vb script without using windows tool options,

  17. Shafeeq

    Good JOb guys.

  18. rem ********************************
    rem delete cookies

    call fn_DeletesubFolderAndFiles(“C:\DOCUME~1\%USERNAME%\Cookies”)
    rem *********************************

    rem delete Temporary internet files
    call fn_DeletesubFolderAndFiles(“C:\DOCUME~1\%USERNAME%\Locals~1\Tempor~1″)
    rem ***********************************

    REM *************************************************************************
    REM Function fn_DeletesubFolderAndFiles(path)
    Rem this Function delete the files & subfolder under the specified path
    REM Input spath := Files path or parent Folder path
    REM Output(ReturnType) := None
    REM Note := IF file Protected then it will not delete without giving Error
    REM Created: 17/April/2009 Rajiv Kumar Nandvani ## Changed:MM/DD/YYYY

    REM *************************************************************************

    Public Function fn_DeletesubFolderAndFiles(spath)
    on Error Resume Next
    rem Create File System object
    set objFileSystem = CreateObject(“Scripting.FileSystemObject”)
    rem Create Window Shel object
    Set objWshShell = CreateObject(“WScript.Shell”)
    Rem get Folderpath under which file present
    Set objoFolder = objFileSystem.GetFolder(objWshShell.ExpandEnvironmentStrings(spath))
    rem get count the files under the folder and loop run for delete the files
    For Each oFile In objoFolder.files
    On Error Resume Next
    objFileSystem.DeleteFile oFile
    Err.clear
    Next
    rem get count the subfolders under the folder and loop run for delete the subfolders
    For Each oSubFolder In objoFolder.SubFolders
    On Error Resume Next
    objFileSystem.DeleteFolder oSubFolder
    Err.clear
    Next
    rem clear the object
    set objFileSystem = nothing
    set objWshShell = nothing
    set objoFolder = nothing
    Err.clear
    End function

  19. Suresh

    how to check log files?

  20. K Subba Raju (Delete a cookie)

    Browser(“Browser”).WinToolbar(“ToolbarWindow32″).Press “&Tools”
    Browser(“Browser”).WinToolbar(“ToolbarWindow32″).Press “&Tools”
    Browser(“Browser”).WinMenu(“ContextMenu”).Select “Delete Browsing History…”
    Browser(“Browser”).Dialog(“Delete Browsing History”).WinButton(“Delete cookies”).Click
    Browser(“Browser”).Dialog(“Delete Browsing History”).Dialog(“Delete Cookies”).WinButton(“Yes”).Click
    Browser(“Browser”).Dialog(“Delete Browsing History”).WinButton(“Close”).Click

  21. Praj

    Function Deletecookies
    userName=Environment.Value(“UserName”)
    Dim oShell
    Set oShell=CreateObject(“WScript.shell”)
    oShell.run(“cmd /C cd C:\Documents and Settings\” & userName & “\cookies & del *.txt”)
    Set oshell=nothing
    End Function

  22. zubair

    try
    webutil.deletecookies

    :)

  23. Andrey Koshkarov

    Hi
    For IE7 browser I use next function:
    Sub ClearCookies()
    ‘work only for IE7
    Set wshshell = CreateObject(“WScript.Shell”)
    WshShell.Run “Rundll32.exe InetCpl.cpl, ClearMyTracksByProcess 255″, 1, true
    End Sub

    To read more about clearing IE7 history from command line go to next URL:
    http://www.howtogeek.com/howto/windows/clear-ie7-browsing-history-from-the-command-line/

  24. Sumit Kalra

    below is the general code to delete cookies by creating shell obj.:
    Const COOKIES = &H21&
    Set objShell = CreateObject("Shell.Application")
    Set objFolder = objShell.Namespace(COOKIES)
    Set objFolderItem = objFolder.Self
    strPath = objFolderItem.Path & "\*.*"
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    objFSO.DeleteFile(strPath)

    but u can delete without creating shell obj… forget that code :(

  25. Sumit Kalra

    Ankur – without creating shell object.. u can delete cookies by VBscript..

    using the above code u prepare a vbscript to delete files.. i used that script around 1 year back in my project.. now i am unable to remember the exact code.. the script was just of 5-6 lines.. can you help me in this code..

  26. Sumit Kalra

    below are the constants for special folders in windows:

    &H1& Internet Explorer

    &H2& Programs

    &H3& Control Panel

    &H4& Printers and Faxes

    &H5& My Documents

    &H6& Favorites

    &H7& Startup

    &H8& My Recent Documents

    &H9& SendTo

    &Ha& Recycle Bin

    &Hb& Start Menu

    &Hd& My Music

    &He& My Videos

    &H10& Desktop

    &H11& My Computer

    &H12& My Network Places

    &H13& NetHood

    &H14& Fonts

    &H15& Templates

    &H16& All Users Start Menu

    &H17& All Users Programs

    &H18& All Users Startup

    &H19& All Users Desktop

    &H1a& Application Data

    &H1b& PrintHood

    &H1c& Local Settings\Application Data

    &H19& All Users Favorites

    &H20& Local Settings\ Temporary Internet Files

    &H21& Cookies

    &H22& Local Settings\History

    &H23& All Users Application Data

    &H24& Windows

    &H25& System32

    &H26& Program Files

    &H27& My Pictures

    &H28& User Profile

    &H2b& Common Files

    &H2e& All Users Templates

    &H2f& Administrative Tools

    &H31& Network Connections

  27. Sumit Kalra

    Ankur – please ignore my previous comments..
    below is the code of cookies
    COOKIES = &H21&

  28. Sumit

    Hi Ankur,
    there is 1 more code to delete TEMp files,COOKIES using SHELL codes.

    COOKIES = 0x21

    using the above code u prepare a vbscript to delete files.. i used that script around 1 year back in my project.. now i am unable to remember the exact code.. the script was just of 5-6 lines.. can you help me in this code..

  29. maddy

    @ankur : i need to clarify one doubt when u said to manjula that “How about reaching the cookies directory directly through the shell object you created and deleting all the files inside? That will reduce the length of code to a single statement” ?
    how to achieve this ?

  30. Ankur

    @itpayz, Basim: Nice solutions.

    @Maniz: Good one. Webutil is an undocumented method (for some unknown reasons!)

    @Manjula: How about reaching the cookies directory directly through the shell object you created and deleting all the files inside? That will reduce the length of code to a single statement.

    @Will: :) Same here. By the way for quite some time I have not seen any updates on your blog… trust everything is fine?

  31. Will

    It’s interesting to see the solutions here. It wouldn’t have even occurred to me to write a script that actually clicks through the IE menu items to do it.

  32. Maniz

    We can use WebUtil.(Method)

    webutil.DeleteCookie
    webutil.DeleteCookies

  33. Basim

    'key codes
    Const VK_RETURN = 28
    Const VK_CONTROL = 29
    Const VK_DOWN = 80

    Dim oBrowser
    Set oBrowser = Description.Create()
    oBrowser( "micClass" ).Value = "Browser"
    'oBrowser( "title" ).Value = "about:blank"
    oBrowser( "application version" ).Value = "internet explorer 7"
    oBrowser( "version" ).Value = "internet explorer 7"

    Set BrowserObject = Browser(oBrowser).object
    Set deviceReplay = CreateObject( "Mercury.DeviceReplay" )
    Window("hwnd:=" & BrowserObject.hwnd).activate
    Window("hwnd:=" & BrowserObject.hwnd).Type micNumLockOff
    Window("hwnd:=" & BrowserObject.hwnd).Type micAltDwn + "t"+ micAltUp
    wait(1)

    ' deviceReplay.PressNKeys VK_DOWN , sIndex
    wait(1)

    deviceReplay.PressKey VK_RETURN

    Browser("Browser").Dialog("Delete Browsing History").WinButton("Delete cookies").Click
    wait(1)
    Browser("Browser").Dialog("Delete Browsing History").Dialog("Delete Cookies").WinButton("Yes").Click
    wait(1)
    Browser("Browser").Dialog("Delete Browsing History").WinButton("Close").Click

  34. Manjula

    '##################################
    '#Function ID/Name: ClearCookies
    '#Function Description:The Function clears all cookies that are present on your HardDrive in an Internet Transaction. '#Function Logic: The function opens the Properies Window of Internet Explorer & fires the Click Event for the Delete Cookies ' Button & Delete Temporary Internet Files.
    '
    ' Example
    '
    ' Call ClearCookies()
    '
    '#Author: Manjula Palnati
    '##################################

    Function ClearCookies()
    SystemUtil.Run "Control.exe","inetcpl.cpl"
    Set objShell = CreateObject("Wscript.Shell")
    Do Until Success = True
    Success = objShell.AppActivate("Internet Properties")
    Wait(1)
    Loop
    objShell.Sendkeys "%i"
    Wait(1)
    objShell.Sendkeys "{ENTER}"
    Wait(1)
    objShell.Sendkeys "%f"
    Wait(1)
    objShell.Sendkeys "%d"
    Wait(1)
    objShell.Sendkeys "{ENTER}"
    Wait(4)
    objShell.Sendkeys "{ENTER}"
    End Function

  35. itpayz

    Browser("Browser").WinToolbar("ToolbarWindow32").Press "&Tools"
    Browser("Browser").WinToolbar("ToolbarWindow32").Press "&Tools"
    Browser("Browser").WinMenu("ContextMenu").Select "Delete Browsing History…"
    Browser("Browser").Dialog("Delete Browsing History").WinButton("Delete cookies").Click
    Browser("Browser").Dialog("Delete Browsing History").Dialog("Delete Cookies").WinButton("Yes").Click
    Browser("Browser").Dialog("Delete Browsing History").WinButton("Close").Click

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>