Add HTML on an injected iframe

2019-04-11 10:29发布

I'm currently developing a Toolbar from Google Chrome. Basically it's a toolbar that i'm injecting in every web pages by using a Content-Script. Technically the toolbar is materializd by a iframe that include all the components like button, dropMenu,... Here is the script you make this :

// Take down the webPage

document.getElementsByTagName('body')[0].style.marginTop = '39px';

var body = $('body'),
toolbarURL = chrome.extension.getURL("yourtoolbar.html"),
iframe = $('<iframe id="YourToolbarFrame" scrolling="no" src="'+toolbarURL+'">');

// Insertion
body.append(iframe);    

// Effect
$("#YourToolbarFrame").hide().fadeIn(800);

But right now i'm trying to add some component on this iframe for example a button but it didn't work...

var yt = $("#YourToolbarFrame");
var newButton = $('<a href="javascript:openInstantMessage()"><input type="image" src="images/pop.ico" name="InstantMessage" width="23" height="23"></a>');
yt.append(newButton);

The body of the iframe look like this :

<body>          
    <div class="default">
         // COMPONENTS
    </div>
</body>      

Hope someone can provide me some help ! :)

2条回答
祖国的老花朵
2楼-- · 2019-04-11 10:33

You have to wait until the iframe loaded. E.g.:

iframe.load(function() {  
    var newButton = ...;  
    $(this).contents().find('body').append(newButton);
}).appendTo('body');

Not sure how Chrome handles the same-origin policy for content scripts though.

查看更多
不美不萌又怎样
3楼-- · 2019-04-11 10:53

Since you're using jQuery, you could try using

$('#YourToolbarFrame').contents().find('body').append(newButton);

Or if you don't want to append to the body directly, use any other element in the find() statement.

查看更多
登录 后发表回答