开发者

Google Chrome Extension: Passing javascript variable to iframe src

开发者 https://www.devze.com 2023-03-29 15:31 出处:网络
I have added \"tabs\" in permissions but this code doesnt work . The iframe works when the url is passed directly but not from the script.

I have added "tabs" in permissions but this code doesnt work . The iframe works when the url is passed directly but not from the script.

    <html> 
    <head> 
    </head>
    <body >
    <iframe src="www" id="link" width="400" height="300">
    <p>Your browser does not support iframes.</p>
    </iframe>
    <script>
    var url1="xxx";
    chrome.tabs.getSelected(null,function(tab) {
    var url1= tab.url;
    });
    document.getElementById("link").src=url1;
    </scrip开发者_C百科t>
    </body>
    </html>


Let me see if I understand the question.

You would need to add to your content script manifest the permission to access that page that has the iframe. Once you do, you use Content Scripts and its Message Passing to pass data to that iframe.

In the example above, you would need to inject a content script, so in your manifest:

"content_scripts": [{
    "matches": ["https://www.my.injected.url/*"],
    "js": ["injected_script_that_has_the_iframe.js"],
    "run_at": "document_end",
    "all_frames": true
}]

Then in that content script, you can do normal JavaScript to set the URL:

document.getElementById("link").src= someURL;

Now, where is that URL coming from? Is it coming from your extension? If so, use Message Passing to request that.

chrome.extension.sendRequest({method: "GetURL"}, function(response) {
  document.getElementById("link").src= response.url;
});

And within your background page, you listen for requests coming from your background page:

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
    if (request.method == "GetURL")
      sendResponse({url: "http://rim.com"});
    else
      sendResponse({}); // snub them.
});

To recap, your content script asks your extension (background page), what the URL is, and once it gets a response, it updates the iframe.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号