【问题标题】:run js script in chrome extension on page load在页面加载时在 chrome 扩展中运行 js 脚本
【发布时间】:2017-03-26 13:03:12
【问题描述】:

我需要构建一个 chrome 扩展来操作 dom 我正在关注一些教程,现在 我有这个 manifest.json:

{
  "manifest_version": 2,

  "name": "Getting started example",
  "description": "This extension shows a Google Image search result for the current page",
  "version": "1.0",

  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  },
  "permissions": [
    "activeTab",
    "https://ajax.googleapis.com/"
  ]
}

这是我的 popup.html:

<!doctype html>
<!--
 This page is shown when the extension button is clicked, because the
 "browser_action" field in manifest.json contains the "default_popup" key with
 value "popup.html".
 -->
<html>
  <head>
    <title>Getting Started Extension's Popup</title>
    <style>
      body {
        font-family: "Segoe UI", "Lucida Grande", Tahoma, sans-serif;
        font-size: 100%;
      }
      #status {
        /* avoid an excessively wide status text */
        white-space: pre;
        text-overflow: ellipsis;
        overflow: hidden;
        max-width: 400px;
      }
    </style>

    <!--
      - JavaScript and HTML must be in separate files: see our Content Security
      - Policy documentation[1] for details and explanation.
      -
      - [1]: https://developer.chrome.com/extensions/contentSecurityPolicy
     -->
    <script src="popup.js"></script>
    <script type="text/javascript">console.log('attempt #0 to console log something');</script>
  </head>
  <body>
    <div id="status"></div>
    <img id="image-result" hidden>
  </body>
</html>

这是我的 popup.js:

document.addEventListener('DOMContentLoaded', function() {
  console.log('attempt #3');
});


chrome.tabs.onUpdated.addListener(
function ( tabId, changeInfo, tab )
{ 
  if ( changeInfo.status === "complete" )
  {
    chrome.tabs.executeScript({ code: "console.log('attempt #4');" }, function() {
       console.log("console.log(attempt #5)");
   });
  }
});

如您所见,我尝试了各种方法在页面加载后控制台记录某些内容,但它们都不起作用 我该怎么办?

【问题讨论】:

  • 对我来说他们都在工作:document.addEventListener('DOMContentLoaded', function() { console.log('attempt #3'); }); window.onload=function(){ console.log("test"); } 。请注意您在弹出窗口的控制台中而不是在页面控制台中进行检查!
  • @OriEng 我需要在真实页面中操作 DOM,而不是弹出窗口。那我该怎么做???
  • 好的,我明白了。所以你想等到一些页面加载然后在那里做一些事情..那么你的弹出窗口如何相关?您想要扩展工作的特定地址吗?为什么不使用内容和背景脚本? ,然后您可以将消息从后台发送到您的页面正在加载的内容。
  • so how your pop-up related here - 弹出窗口不相关 - 这只是我一直在关注的教程。这就是我使用它的原因。 You want specific address that the extension work no - 是的,具体地址。 why you don't use content and background scripts - 实际上现在我正试图让它与后台脚本一起工作。但是我遇到了 manifest.json 文件的一些问题。你能提供 manifest.json 的正确工作示例吗?

标签: javascript jquery google-chrome google-chrome-extension


【解决方案1】:

所以我认为简单的解决方案就是创建一个内容脚本,然后等待页面加载:

manifest.json

{
    "manifest_version": 2,
    "name": "Getting started example",
    "description": "This extension shows a Google Image search result for the   current page",
    "version": "1.0",
    "content_scripts": [
        {
            //Set your address you want the extension will work in mataches!!!
            "matches": ["http://mail.google.com/*", "https://mail.google.com/*"],
            "js": ["content.js"],
            "run_at": "document_end"
        }
    ],
    "permissions": ["activeTab", "https://ajax.googleapis.com/"],
    "browser_action": {
        "default_icon": "icon.png",
        "default_popup": "popup.html"
    }
}

content.js

window.onload=function(){
     console.log("page load!");
}

您还可以在 background.js 和您的内容页面之间使用消息传递并检查该选项卡是否已加载,但对于您的情况,我认为这已经足够了。

【讨论】:

    【解决方案2】:

    我就是这样做的:

    manifest.json

    ...
    "background": {
        "scripts": [
            "assets/js/background.js"
        ],
        "persistent": false
    },
    ....
    

    background.js

    function openOrFocusOptionsPage() {
        var optionsUrl = chrome.extension.getURL('popup.html'); 
        chrome.tabs.query({}, function(extensionTabs) {
            var found = false;
            for(var i=0; i < extensionTabs.length; i++) {
                if(optionsUrl == extensionTabs[i].url) {
                    found = true;
                    chrome.tabs.update(extensionTabs[i].id, {"selected": true});
                }
            }
            if(found == false) {
                chrome.tabs.create({url: "popup.html"});
            }
        });
    }
    
    chrome.extension.onConnect.addListener(function(port) {
        var tab = port.sender.tab;
    
    
        port.onMessage.addListener(function(info) {
            var max_length = 1024;
            if(info.selection.length > max_length)
                info.selection = info.selection.substring(0, max_length);
            openOrFocusOptionsPage();
        });
    });
    
    
    chrome.browserAction.onClicked.addListener(function(tab) {
        openOrFocusOptionsPage();
    });
    

    【讨论】:

    • 你能发布 manifest.json 的更新和完整代码吗,因为谷歌浏览器在我更改时会说“无法加载清单 json 文件”
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-20
    相关资源
    最近更新 更多