2015-10-30 29 views
0

如何仅在网站的子目录中加载Chrome内容脚本。例如:仅在网站的子目录中加载内容脚本

在:https://www.example.com/#!/video/*
不在:https://www.example.com/

所以我不想在主页上,而是在视频目录加载。我尝试过这样的匹配模式,但它不起作用。

"matches": ["*://*.example.com/*", "*://*.example.com/#!/video/*"]

我的网址是这样的:www.example.com/#!/video/random_numbers/some-random-string

PS:我也想从页面的每Ajax请求后重新加载脚本。

回答

1

问题是在"matches"中不支持URL片段(URL哈希),并且无法使用"content_scripts"节自动注入/自动移除基于哈希更改的脚本,因为页面实际上没有重新加载。

从manifest.json中删除整个"content_scripts"部分,并使用webNavigation API仅在需要时注入/激活内容脚本(需要"permissions: ["webNavigation"])。

  • background.js:

    chrome.webNavigation.onCommitted.addListener(function(details) { 
        injectOrActivate("onCommitted", details); 
    }); 
    chrome.webNavigation.onHistoryStateUpdated.addListener(function(details) { 
        injectOrActivate("onHashChange", details); 
    }); 
    
    function injectOrActivate(event, details) { 
        var tabId = details.tabId; 
    
        if (details.url.indexOf("#") < 0) { 
         deactivateContentScript(tabId); 
         return; 
        } 
    
        chrome.tabs.executeScript(tabId, {code: "injectedStatus"}, function(res) { 
         if (res[0] != "injected") { 
          chrome.tabs.executeScript(tabId, {file: "content.js"}, function(res) { 
           activateContentScript(tabId); 
          }); 
         } else { 
          activateContentScript(tabId); 
         } 
        } 
    } 
    
    function activateContentScript(tabId) { 
        chrome.tabs.sendMessage(tabId, {action: "activate"}); 
    } 
    
    function deactivateContentScript(tabId) { 
        chrome.tabs.sendMessage(tabId, {action: "deactivate"}); 
    } 
    
  • content.js:

    var injectedStatus = "injected"; 
    chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) { 
        switch (msg.action) { 
         case "activate": 
          doSomething(); 
          break; 
         case "deactivate": 
          stopDoingSomething(); 
          break; 
        } 
    }); 
    
+0

删除''' “*://*.example.com/*”' ''也没有帮助。 – Zip

+0

噢,对不起,看到更新的答案 – wOxxOm

+0

另一种方式是常规的内容脚本,只通过观看它的变化来做基于当前网址的东西。另外,通过ajax处理稍后页面更改的部分已经在s.o中进行了介绍。 –