2014-12-09 91 views
2

我试图删除缓存,当用户去这个网址stackoverflow.com/?clear然后重新装入,然后转到stackoverflow.com与干净的缓存,我尝试了很多方法,但我失败了。从Chrome浏览器会自动缓存时匹配网页URL

这是我最后一次尝试,它根本不影响缓存!

清单代码

{ 
    "name": "stackoverflow", 
    "version": "1.0", 
    "background": { 
    "scripts": ["jquery.js","background.js"], 
    "persistent": false 
    }, 
    "page_action" : 
    { 
    "default_icon" : "icon.png", 
    "default_title" : "Remove" 
    }, 
    "permissions" : [ 
    "declarativeContent", "browsingData", "tabs" 
    ], 
    "manifest_version": 2 
} 

background.js

chrome.runtime.onInstalled.addListener(function() { 
    // Replace all rules ... 
    chrome.declarativeContent.onPageChanged.removeRules(undefined, function() { 
    // With a new rule ... 
    chrome.declarativeContent.onPageChanged.addRules([ 
     { 
     // That fires when a page's URL contains a 'stackoverflow.com/?clea' ... 
     conditions: [ 
      new chrome.declarativeContent.PageStateMatcher({ 
      pageUrl: { urlContains: 'stackoverflow.com/?clear' }, 
      }) 
     ], 
     // And shows the extension's page action. 
     actions: [ new chrome.declarativeContent.ShowPageAction() ] 
     } 
    ]); 
    }); 
}); 

function clearMe(tab) { 
    var ms = (30 * 60) * 1000; // 30 minutes 
    var time = Date.now() - ms; 
    chrome.browsingData.removeCache({"since": time}, function() { 
     chrome.tabs.update({url: 'http://stackoverflow.com'}); 
    }); 
} 
//It will be perfect if user do not have to click 
chrome.pageAction.onClicked.addListener(clearMe) 



我需要更好的选择要删除缓存,甚至没有用户点击一个按钮。

+0

我不认为你可以从JavaScript清除浏览器缓存。这是一个用户驱动的事件 – jsHero 2014-12-09 13:13:41

+0

@jsHero我正在使用Chrome API'chrome.browsingData.removeCache'[READ MORE](https://developer.chrome.com/extensions/browsingData#method-removeCache) – Jim 2014-12-09 13:15:46

+0

@jsHero魔术字“Chrome API” – Xan 2014-12-09 13:15:59

回答

3

tabs api应该足够了。这是你应该怎么做的。我测试过了,它工作正常。

清单代码

{ 
    "name": "stackoverflow", 
    "version": "1.0", 
    "background": { 
    "scripts": ["background.js"], 
    "persistent": false 
    }, 
    "permissions" : [ 
    "tabs", "browsingData" 
    ], 
    "manifest_version": 2 
} 

background.js

chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) { 
    // if url is changed 
    if (changeInfo.url) { 
    var url = changeInfo.url; 

    if (url.indexOf("stackoverflow.com/?clear") != -1) { 
     alert("Clearing cache..."); 
     clearMe(tab); 
    } 
    } 
}); 

function clearMe(tab) { 
    var ms = (30 * 60) * 1000; // 30 minutes 
    var time = Date.now() - ms; 
    chrome.browsingData.removeCache({"since": time}, function() { 
    chrome.tabs.update(tab.id, { url: 'http://stackoverflow.com' }); 
    }); 
}