最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - run js script in chrome extension on page load - Stack Overflow

programmeradmin3浏览0评论

I need to build a chrome extension that manipulates dom I am following some tutorial and now I have this 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",
    "/"
  ]
}

This is my 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]: 
     -->
    <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>

And this is my 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)");
   });
  }
});

As you can see I tried various ways to console log something after page loaded but none of them work what do I do?

I need to build a chrome extension that manipulates dom I am following some tutorial and now I have this 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/"
  ]
}

This is my 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>

And this is my 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)");
   });
  }
});

As you can see I tried various ways to console log something after page loaded but none of them work what do I do?

Share Improve this question asked Mar 26, 2017 at 13:03 user2950593user2950593 9,62719 gold badges74 silver badges138 bronze badges 4
  • For me both of them is working: document.addEventListener('DOMContentLoaded', function() { console.log('attempt #3'); }); window.onload=function(){ console.log("test"); } . Just Put attention that you check in the console of the pop-up and not in page console! – OriEng Commented Mar 26, 2017 at 13:48
  • @OriEng I need to manipulate DOM in real page, not popup. So how Do I do this??? – user2950593 Commented Mar 26, 2017 at 13:59
  • OK now I understand . So you want to wait until some page load and then make some things there.. 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? , then you could send message from background to content that your page is load. – OriEng Commented Mar 26, 2017 at 14:03
  • so how your pop-up related here - popup is not related - it is just a tutorial I've been following. That is why I use it. You want specific address that the extension work no - yes, specific address. why you don't use content and background scripts - Well actually right now I am trying to make it work with background scripts. But I get some problems with manifest.json file. Can you provide proper working example of manifest.json ? – user2950593 Commented Mar 26, 2017 at 14:11
Add a comment  | 

2 Answers 2

Reset to default 13

So I think that the simple solution is just to create a content script and there to wait until the page is load :

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!");
}

You could also use with message passing between background.js and your content page and to check that tab is loaded but for your case I think it's enough.

This is how I do:

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();
});
发布评论

评论列表(0)

  1. 暂无评论