简体   繁体   中英

Access current tab's DOM from dynamically injected Iframe from extension & update iframe DOM

I am developing an extension which adds a custom toolbar at the top of each page. To do this I am injecting toolbar.html from the extension. Since I am a beginner, I am not sure how I can access DOM elements of the current tab and how to to update the newly added iframe with the data from the current tab's DOM.

Here is the manifest:

{
  "manifest_version": 2,

  "name": "My Extension",
  "description": "Extension to show custom toolbar",
  "version": "1.0",

  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  },
  "background":{
      "scripts":["background.js"]
  },
  "content_scripts":[{
      "matches":["https://bitbucket.mycompany.com/*"],
      "css":["styles.css"],
      "js":["jquery.js","myscript.js"],
      "all_frames":true
  }],
    "web_accessible_resources":[
        "toolbar.html",
        "styles.css"
    ]
}

Content script is myscript.js

var url=chrome.extension.getURL('toolbar.html');
var height='35px';
var iframe="<iframe src='"+url+"' id='myCustomBar' style='height:"+height+"'></iframe>"

$('html').append(iframe);

$('body').css({
    'transform':'translateY('+height+')'
});

My questions are :

  1. If I use a separate content script (Answered here: access iframe content from a chrome's extension content script ) for the iframe, what should be the URL matches?
  2. Are there any other ways of accessing the current tab's DOM from a dynamically injected iframe?
  3. Suppose I need this extension to run on all the URLs which have a URL pattern like https://bitbucket.*.com , what should be the matches?
  1. You can't use a separate content script for that iframe, since the src for the iframe is starting with chrome-extensions:// which is not allowed to inject content scripts into by default.

  2. You could include a script tag for toolbar.html , then use Window.postMessage to do message passing between toolbar.js and parent content scripts.

  3. According to Match patterns , if '*' is in the host, it must be the first character. So you may want to use something like https://*.com and check the other parts in your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM